Search code examples
androiddartflutterback-button

Flutter Android back button navigating back to main page


I would like to be able to use the back button to navigate back to the main page instead of closing the app, I have seen the WillPopScope widget option but that needs to show a dialog, is there a way to pop back using the android back button without a dialog?


Solution

  • You can Use Navigator.canPop() Method to avoid app from Exiting.

    class _MyHomePageState extends State<MyHomePage> {
      @override
      Widget build(BuildContext context) {
        return WillPopScope(
          onWillPop: () async {
            return Navigator.canPop(context);
          },
          child: Scaffold(
            appBar: AppBar(title: const Text('HomePage')),
            floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
            floatingActionButton: FloatingActionButton(
              child: const Icon(Icons.add),
              backgroundColor: Colors.red,
              onPressed: () {
                Navigator.push(
                    context, MaterialPageRoute(builder: (context) => SecondPage()));
              },
            ),
          ),
        );
      }
    }