Skip to main content

How To Override the “Back” Button

Whenever you’re building a mobile app using Flutter, you may come across a situation where you need to override the “back” button. Perhaps you want your users to be able to navigate backward through the app without having to leave it, or maybe there’s a specific screen in your app that you don’t want people to be able to exit from. In either case, overriding the “back” button is an easy way to handle this kind of situation.

class MainAppBar extends StatelessWidget implements PreferredSizeWidget {

  final double barHeight = 20.0;

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

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

  @override
  Widget build(BuildContext context) {

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

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