How to Create a Reusable AppBar with Custom Back Button in Flutter

We don’t always want a material or a cupertino back button in our flutter app. So we use leading property in the appbar to use a custom back button. But there is a problem, it is not reusable and will not automatically handle back button like how Flutter default AppBar widget does. Here we will solve the exact problem by creating a custom AppBar that also hides or shows back button when needed. By handling back button automatically means only show back button when necessary so we don’t have to explicitly tell AppBar to show back button or not.

How AppBar handles back button or any leading widget?

According to documentation of leading property.

If this is null and automaticallyImplyLeading is set to true, the AppBar will imply an appropriate widget. For example, if the AppBar is in a Scaffold that also has a Drawer, the Scaffold will fill this widget with an IconButton that opens the drawer (using Icons.menu). If there’s no Drawer and the parent Navigator can go back, the AppBar will use a BackButton that calls Navigator.maybePop.

https://api.flutter.dev/flutter/material/AppBar/leading.html

And according to documentation of BackButton.

When deciding to display a BackButton, consider using ModalRoute.of(context)?.canPop to check whether the current route can be popped. If that value is false (e.g., because the current route is the initial route), the BackButton will not have any effect when pressed, which could frustrate the user.

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

So considering these two and stealing some snippets from flutter appbar, we can make our custom appbar handle back button automatically in our flutter app.

Breaking down these we have following points.

  • If leading widget is provided we don’t need to do anything and just show that widget.
  • If automaticallyImplyLeading property is true then only we consider handling back button else we don’t care. And
  • if there is an active route below the page then only we show back button.
  • Other than these we don’t care about back button at all.

Which gives us this.

And this is what CustomAppBar looks like.

And CustomBackButton

GitHub link: https://github.com/2shrestha22/flutter_examples/tree/a31aab76809bba7eb6e8702def6752f36cccd035/examples/custom_appbar

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.