fluttergesture

How to prevent app from closing on swipe back


In a screen of my flutter app I have some buttons that allow me to open new pages, created with the following code:

@override
Widget build(BuildContext context) {
  return ElevatedButton.icon(
    onPressed: () {
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (BuildContext context) {
            return Scaffold(
              appBar: AppBar(title: const Text("Back Swipe")),
              body: const Center(
                child: SizedBox(),
              ),
            );
          },
        ),
      );
    },
    icon: const Icon(Icons.sunny),
    label: const Text("Hello"),
  );
}

The problem is that by doing so, once I enter the subpage, to go back I have to click on the back button.

If instead I use the back swipe (from left or right) the app closes.

Adding the rootNavigator: true parameter like this:

Navigator.of(context, rootNavigator: true).push(

the back swipe works and I go back, but using this parameter, the NavigationBar disappears, and I need it to stay.

How can I solve it? Thanks in advance


Solution

  • I finally figured out how to fix this problem!

    It should be added:

    pageTransitionsTheme: const PageTransitionsTheme(
      builders: <TargetPlatform, PageTransitionsBuilder>{
        // Set the predictive back transitions for Android.
        TargetPlatform.android: PredictiveBackPageTransitionsBuilder(),
      },
    ),
    

    inside ThemeData, as explained on predictive-back page