Flutter - How to Prevent Back Button Click in Flutter

In this article, I am going to share with you how to disable the device back button in the Flutter app for Android and IOS. You may need to disable the back button where you don't want to prevent back your app by pressing the back button on the device. In flutter, we can disable the back button using WilPopScope widget.

Syntax:

WillPopScope(
    onWillPop: () async{
      return false;
    },
    child:Scaffold()
)

Just, You need to wrap your whole widget tree with WilPopScope and pass a function that returns "false" on onWillPop properties. Now the user can't able to press the back button. Let's take an example.

class Errorgram extends StatefulWidget {
  const Errorgram({Key? key}) : super(key: key);

  @override
  State<Errorgram> createState() => _ErrorgramState();
}

class _ErrorgramState extends State<Errorgram> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          return false;
        },
        child: Scaffold(
            body: Center(
              child: Container(
                child: Text("Errorgram.com"),
              ),
            )));
  }
}

I hope you like this article.

Tags: