WillPopScope

WillPopScope it is used to intervene with the back button

The WillPopScope widget is used to intercept the back button press on Android devices or the swipe gesture on iOS devices. It takes an onWillPop callback that is executed when the user tries to leave the current screen.

If a Dialog is opened on the screen, the onWillPop callback of the WillPopScope widget can be used to close it instead of exiting the screen. However, if the Dialog is not displayed when the onWillPop callback is executed, the app may crash.

To avoid this issue, the WillPopScope widget should be wrapped in a Builder widget. The Builder widget creates a new BuildContext that is used to show the Dialog. This ensures that the Dialog is displayed in the correct context and avoids any errors.

Here is an example of how to use WillPopScope with Builder:

return MaterialApp(
  home: Builder(
    builder: (BuildContext context) {
      return WillPopScope(
        onWillPop: () async {
          bool result = await showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text("title"),
                content: Text("message"),
              );
            },
          );
          return false;
        },
        child: Scaffold(
          backgroundColor: Color.fromARGB(255, 16, 15, 22),
          body: /* Body of the screen */
        ),
      );
    },
  ),
);

Last updated