How to change default back button icon in Flutter?

Viewed 4902

How I will change the back button icon in flutter using the theme. So it can be reflected throughout the application. I saw multiple options in the theme to change the size and color of the icon. But didn't see the change icon option.

3 Answers

Example:

Scaffold(
  appBar(
    leading: BackButton(), // icon depends on TargetPlattrom
  ),
),

Or you can create your own constant widget basis on IconButton with your own icon settings, than use it as value for leading property. In addition, there is an AppBarTheme class, which can be used when you create instance of ThemeData.

https://api.flutter.dev/flutter/material/AppBarTheme-class.html

P.S. If you look at AppBar source code you see that regular widget CloseButton or BackButton are used. So there is no specific style for it. And you have 2 ways:

  • Create your own global widget and use it in each Scaffold.
  • Subclass Scaffold with your own leading property and use it.
appBar: AppBar(
              automaticallyImplyLeading: false,
              leading: Builder(
                builder: (BuildContext context) {
                  return IconButton(
                    icon: const Icon(Icons.alarm_on), // Put icon of your preference.
                    onPressed: () {
                      // your method (function), 
                    },
                  );
                },
              ),
              title: Text(widget.title),
              centerTitle: true,

The above code will change the default back icon to alarm on icon. You can change it to any thing.

I'm not sure if this is the right way to do this. I'm still learning and I don't know if this will work in all cases. I've done this using VS Code while my app is in development.

I looked up the backbutton references(Shift + Alt + F12) and found the actual button in flutter sdk. I changed it there in the back_button.dart file which can be found in your flutter installation folder : c:\flutter\packages\flutter\lib\src\material\back_button.dart

There, edit the static IconData method of the button and choose any Icon you wanna use for any platform.

  static IconData _getIconData(TargetPlatform platform) {
    switch (platform) {
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
        return Icons.arrow_back_ios;
    }
  }

In the above case Icons.arrow_back_ios will be returned in all platforms. You can specify the return Icon for each platform.

However, I haven't tested this in like a real world "production use" situation so I hope someone else here can clarify.

Related