Flutter Error

Override Or Disable Back Button Flutter Appbar – The Easy Way

Learn how to override/disable back button pressed in flutter applications to make your app standout from the rest. Why because, whiles users are interacting with your app, they might accidentally press on the back-button in android operating systems (OS). And guess what will happen when such button is clicked! If the user is on the home screen/page of your application, it will be terminated. But if they are in any other screen apart from the home screen, then it will not exit the app but it will rather navigate them back to the previous screen.

Is this really the best? No, as a programmer you have to have full control of your Flutter apps to a point where you could disable android back button. And the best option is to show a dialog asking the user if he/she want to exit the app on back button pressed.

Below is an example of how it works:

flutter disable android back button pressed

Disable Android Back Button in Flutter Apps

The Flutter WillPopScope widget provide a callback detail of the android OS whenever the back button is pressed. Because of it continuous provision of the details through the callback we can disable the back-button on pressed. Within the callback we have an option to return a Boolean value, that’s true/false. Returning false will disable the back button and true will make the screen popped.  

Step by step way to do it:

Step 1: Your Scaffold() widget of your activity needs to be wrapped with the WillPopScope widget for it to work.

Step 2: You need a method to handle the on back button pressed called in the WillPopScope widget. So, what you should do is to create a method and assign it to the onWillPop parameter.

Step 3: Then simply return false in the callback. Remember what I said earlier “returning false will disable the back button but true will make the screen popped”

class _MyFlutterApp State extends State<MyFlutterApp> {

  Future<bool> _onWillPop() async {
    // return false here to disable to back button
    return false;
  }

  @override
  Widget build(BuildContext context) {
  // Wrap your scaffold with WillPopScope widget
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(title:Text(“flutter disable android back button example”)),
        body: Center(
          child: Column(
            children: [
              SizedBox(
                height: 20,
              ),
              Text(
                'App Welcom Screen',
                style: TextStyle(fontSize: 30),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Flutter Override/detect Back Button and show exist confirmation dialog

You can use the WillPopScope widget to override the back button on pressed and show a confirmation dialog to the user to decide either to terminate the app or continue using it. For this to work, you have to apply a simple logic. You need to open a self-executing dialog whenever the back button is pressed in the onWillPop call back method. You can then exit the app when the user clicks on YES, and hide the dialog when user clicks NO.

Example code for overriding the android back button in flutter:

Step 1: Wrap your parent widget which is the Scaffold() with the WillPopScope widget. This will invoke it call back when the user is on that particular screen.

Step 2: Again, just as we did earlier, you need to create a method and assign it to the onWillPop parameter to indicate what to do when the back button is pressed.

Step 3: Then inside the callback method created in option 2 above, return/show AlertDialog with YES and NO options using the TextButton.

Step 4: Then simply return Navigator.of(context).pop(false) inside the onPressed() callback of the TextButton with NO option.

Step 5:  Finally return Navigator.of(context).pop(true) In the onPressed() callback of the TextButton with YES option.

class _MyFlutterAppState extends State<MyFlutterApp> {

// we will pass this method as an argument so that it will be invoked when the back button is pressed
Future<bool> _onWillPop() async {
  return (await showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: new Text('Are you sure?'),
          content: new Text('Do you want to exit the App'),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),// pass in false to the pop() method
              child: new Text('No'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true), // pass in true to the pop() method
              child: new Text('Yes'),
            ),
          ],
        ),
      )) ??
      false;
}

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: ...
        body: Center(
          child: Column(
            children: [
              SizedBox(
                height: 20,
              ),
              Text(
                'Welcome screen',
                style: TextStyle(fontSize: 40),
              ),
              Text(
                                    ' how to override back button in flutter',
                style: TextStyle(fontSize: 20),
              ),

            ],
          ),
        ),
      ),
    );
  }
}

How do I turn off back press in Flutter?

To turn off the back button press in flutter simply apply the above logic by wrapping your scaffold with WillPopScope widget.  Then inside the onWillPop callback method, don’t do anything or simply return false.

class _MyFlutterApp State extends State<MyFlutterApp> {

  Future<bool> _onWillPop() async {
    // return false here to turn off back press
    return false;
  }

  @override
  Widget build(BuildContext context) {
  // Wrap your scaffold with WillPopScope widget
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(title:Text(“Flutter turn off back press example”)),
        body: Center(
          child: Column(
            children: [
              SizedBox(
                height: 20,
              ),
              Text(
                'App Welcom Screen',
                style: TextStyle(fontSize: 30),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

How do I disable the back button in Flutter AppBar?

To disable the back button in flutter AppBar simply set automaticallyImplyLeading: false in the AppBar() Widget. Below is a full example:

// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // hide the debug banner from the app
        debugShowCheckedModeBanner: false,
        title: 'dartandflutter.com tutorials',
        theme: ThemeData(
          primarySwatch: Colors.red,
        ),
        home: const HomePage());
  }
}

// Home Page
class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('dartandflutter.com tutorials'),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text('Go to OtherPage'),
          onPressed: () {
            Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => const WelcomePage()));
          },
        ),
      ),
    );
  }
}

// Other Page
class WelcomePage extends StatelessWidget {
  const WelcomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // show the snackbar with some text when back button pressed
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text('The System Back Button is Deactivated')));
        return false;
      },
      child: Scaffold(
        appBar: AppBar(
          // this will disable the appbar back press
          automaticallyImplyLeading: false,
          centerTitle: true,
          title: const Text('Welcome Page'),
        ),
        body: const Center(
          child: Text(
            'Are you looking for a way to go back to Home Screen? Hmm...',
            style: TextStyle(fontSize: 34),
          ),
        ),
      ),
    );
  }
}

Related Posts

disable back button flutter

Solve the method ‘setState’ isn’t defined for the class MyApp error in Flutter

You can solve the error The method ‘setState’ isn’t defined for the class MyApp error in Flutter by simply creating your own StatefulWidget widget. The main reason whey…

flutter-error-setstate-called-after-dispose

Flutter error: setState() called after dispose()

When building apps with Flutter framework you will often encounter this common error “Unhandled Exception: setState() called after dispose() or during build.” This exception is related to something…

disable back button flutter

How to Shift Focus to Next TextField in Flutter

Learn how to shift focus to the next TextField or TextFormField in flutter applications. The whole idea is that when you’re done typing text in one TextField, we…

working with list in Dart/Flutter

Null check operator used on a null value – flutter

The “Null check operator used on a null value” error occurs in flutter apps when you unintentionally access a variable that has a null value. For example, if…