Skip to main content

How To Override the Back Button in AppBar (Change Color, onPressed Event) in Flutter

AppBar is a widget that is typically used as the topmost component of the app for important screen components like app title, actions, etc. It is easy to create an AppBar with a default leading button and actions. But AppBar also provides specialized widgets like IconButton and PopupMenuButton to perform specific actions on press.

The Back button on the left side of the AppBar is a built-in widget that automatically performs the correct action to navigate to the previous screen. However, sometimes you may want to override the default behavior of the Back button. For example, if you have a multi-step form, you may want to go back to the previous step instead of closing the form when the user presses the Back button on AppBar.

In this post, we’ll see how to override the default behavior of the Back button in AppBar.

class MainAppBar extends StatelessWidget implements PreferredSizeWidget {

  final double barHeight = 20.0;

  const MainAppBar({Key? key}) : super(key: key);

  Size get preferredSize => Size.fromHeight(kToolbarHeight + barHeight);

  Widget build(BuildContext context) {

    return AppBar(
      elevation: 0,
      centerTitle: true,
      leading: ModalRoute.of(context)!.canPop ?
        icon: const Icon(
          color: Colors.white,
        onPressed: () =>
      ) : null,
      title: Column(
        children: [
          const Text('App Title')

By continuing to use the site, you agree to the use of cookies.