How to change the default appbar buttons for the whole app

1.1k views Asked by At

I need to change implement custom Icons for default button and drawer button for all pages in my project.

I know we have the option of using leading property, however, this only affects that certain page.

How can we change the default back button and open drawer button of AppBar in Flutter for the whole app?

1

There are 1 answers

1
Suat Özkaya On

Unfortunately, there is not a property called defaultBackButton or defaultDrawerButton.

So, in order to change these defaults in the whole app, we can create a CustomAppBar which and set Icons as we wish.

Please click here to see Demo on DartPad and test it yourself.

For a bit longer description, checkout my Medium story.

class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  final Widget? leading;
  final Widget? title;
  final bool? centerTitle;
  final bool automaticallyImplyLeading;

  const CustomAppBar({
    Key? key,
    this.leading,
    this.title,
    this.centerTitle,
    this.automaticallyImplyLeading = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    /// This part is copied from AppBar class
    final ScaffoldState? scaffold = Scaffold.maybeOf(context);
    final bool hasDrawer = scaffold?.hasDrawer ?? false;
    final ModalRoute<dynamic>? parentRoute = ModalRoute.of(context);
    final bool canPop = parentRoute?.canPop ?? false;

    Widget? leadingIcon = leading;

    if (leadingIcon == null && automaticallyImplyLeading) {
      if (hasDrawer) {
        leadingIcon = IconButton(
          icon: const Icon(Icons.mood_sharp, color: Colors.yellowAccent),
          onPressed: () => Scaffold.of(context).openDrawer(),
        );
      } else {
        if (canPop) {
          leadingIcon = IconButton(
            onPressed: () => Navigator.of(context).pop(),
            icon: const Icon(
              Icons.sentiment_dissatisfied_sharp,
              color: Colors.red,
            ),
          );
        }
      }
    }

    return AppBar(
      leading: leadingIcon,
      title: title,
      centerTitle: centerTitle,
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}