💻
Flutter documentation
  • Flutter documentation
    • Starting an App
    • Import
  • Visual Studio Code
  • Widgets
    • Stateless Widget
    • Stateful Widget
    • Scaffold
    • Text
      • OverFlow
      • Rounded background text
    • Padding
    • Align
    • DraggableScrollableSheet
    • Container
    • Decorated box
    • Expanded
    • IntrinsicHeight
    • IntrinsicWidth
    • ListView.builder(...)
    • Buttons
    • Gauge
    • Navigator
      • WillPopScope
    • Web View
    • Divider
    • Future builder
    • Image
      • Cached_network_image
      • Fade In Image
    • ClipOval
    • InkWell
    • Wrap
    • SingleChildScrollView
    • Stack
    • FittedBox
    • DropdownButton
    • ValueListenableBuilder
    • Maps
    • fl_chart
    • Set SystemNavigation Bar Color
    • Onesignal
    • Builder
    • Set orientation
    • SSE
    • Chat
    • Flutter_animate
    • Supabase
      • Android
    • Changing name and package name
    • Sign apk/abb
  • Dart
    • If / Else in one line
    • Functions
  • Others
  • Airtable
Powered by GitBook
On this page
  1. Widgets
  2. Navigator

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 */
        ),
      );
    },
  ),
);
PreviousNavigatorNextWeb View

Last updated 2 years ago