flutter override android back button

How to Disable or Override Back Button in Flutter?

One of the significant concerns of developers is how to disable or override the back button in Flutter. You can utilize several elements to provide better navigation to your app’s users. These include buttons, text fields, cards, checkboxes, dropdowns, etc. 

It is essential to provide users with full control over your app. Similarly, a back button has a vital role in your app’s navigation. Sometimes, if a user taps the back button within your app, it reverts directly to the mobile phone’s menu screen, which negatively impacts user experience. Your app should ask for permission to confirm the exit. Because users may lose their progress within the app if it closes on an accidental tap.

Additionally, if users input some information or data in the app, they may lose it if the back button has mistakenly been pressed. Instead, we should show a dialogue box asking the user to confirm the exit so that the information can be stored properly. 

Let us first know what the WillPopScope widget is, and we will move toward knowing how to disable or override the back button in Flutter.

What is WillPopScope Widget in Flutter?

The WillPopScope is such a useful widget that comes with the Flutter framework. It gives you full control over the back button, allowing you to move between the screens. You can use this widget to either disable or override the back button in Flutter. Moreover, you can prevent certain unwanted conditions that were discussed at the start. Leveraging the WillPopScope widget ultimately enhances the user experience.

How to disable back button in Flutter?

To disable the back button in Flutter, we need to use the WillPopScope widget

Follow these steps to disable back button in Flutter.

Step#01: Wrap the scaffold or widget tree in the WillPopScope widget. 

Step#02: Now add the onWillPop parameter inside the WillPopScope widget and create a function to handle its call back. 

Step#03: Return false inside the callback. The back button will be disabled.

You can also display a text addressing the back button is disabled, just to have a more transparent user experience.

Here is the example code to disable the back button in Flutter.

Code Example

class UserProfile extends StatelessWidget {
  const UserProfile({super.key});

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          backgroundColor: Colors.black,
          title: const Text("WillPopScope"),
        ),
        body: const Center(
          child: Text(
            "Back Button Disabled.",
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.w300),
          ),
        ),
      ),
      onWillPop: () async {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content:
                Text('Pop Screen Disabled. You cannot go to previous screen.'),
            backgroundColor: Colors.red,
          ),
        );
        return false;
      },
    );
  }
}

Result

disable back button in flutter

Now that you learned how to disable the back button in Flutter, you may need to show a dialogue box asking for confirmation whenever a user taps the back button in Flutter. This could be done using AlertDialog, but interestingly, the rest of the steps remain the same.

How to Override Back Button in Flutter? (Display Custom Dialog Box Before Exiting)

To display a custom dialogue box asking the user to confirm its exit, we need to override the back button in Flutter. We use the same WillPopScope widget for this purpose. And the AlertDialog class will display the alert box on the screen as the user taps on the back button. When the user taps the back button, it will show a dialogue box asking for confirmation to exit (Yes/No). If the user presses ‘no’, the dialogue box will disappear, and the user will remain in the app. Whereas, if the user presses ‘yes’, the app will be closed. 

Here is the example code for you to override the back button in Flutter.

Code Example:

class HomePageWillPop extends StatelessWidget {
  const HomePageWillPop({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          backgroundColor: Colors.black,
          title: const Text("Home Page"),
        ),
        body: const Center(
          child: Text(
            "Welcome to Home Page.",
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.w300),
          ),
        ),
      ),
      onWillPop: () async {
        final shouldPop = await showDialog<bool>(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: const Text('Exit'),
              content: const Text('Are you sure you want to exit the app?'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(context, true);
                  },
                  child: const Text('Yes'),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.pop(context, false);
                  },
                  child: const Text(
                    'No',
                    style: TextStyle(color: Colors.red),
                  ),
                ),
              ],
            );
          },
        );
        return shouldPop!;
      },
    );
  }
}

Result

override back button in flutter

Conclusion

You can enhance your app’s user experience by adding certain features and navigation components. As it is one of the major success factors, you should focus on enhancing user experience in every way possible. All you need to do is understand the end-user analyzing its behaviour and needs. Your app will likely succeed in the app store if you keep the user first. Because it’s all about how much your app benefits the users. 

Lastly, it’s a wrap to this quick guide on how to disable or override back button in Flutter. We hope that you would have learnt much out of this. Still, if you have any queries or suggestions, feel free to contact us. We would love to assist you in any Flutter app development projects that you may have. You can also hire flutter developers for your Project

See you in the next blog!

Leave a Comment

Your email address will not be published. Required fields are marked *

Share Post On

Haroon Ashraf

Flutter Developer

Detail-oriented full-stack engineer with 9+ years of industry experience. He’s been working on Flutter since 2018 and has delivered 30+ successful projects.He has experience in project management Trello, Github, Jira…..

Flutter
Xcode
IOS-Swift
Full Stack
Bloc/Cubit
Nodejs

Experience

Availability

9 years

Full-Time

Translate »