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);

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

  @override
  Widget build(BuildContext context) {

    return AppBar(
      backgroundColor: Colors.green,
      elevation: 0,
      centerTitle: true,
      leading: ModalRoute.of(context)!.canPop ?
      IconButton(
        icon: const Icon(
          Icons.arrow_back,
          color: Colors.white,
        ),
        onPressed: () =>
            Navigator.of(context).pop(),
      ) : null,
      title: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const Text('App Title')
        ],
      ),
    );
  }
}

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

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close