Flutter Android back button navigating back to main page

7,998

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()));
          },
        ),
      ),
    );
  }
}
Share:
7,998
Darwish Al-Neyadi
Author by

Darwish Al-Neyadi

Updated on December 06, 2022

Comments

  • Darwish Al-Neyadi
    Darwish Al-Neyadi over 1 year

    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?

    • Rémi Rousselet
      Rémi Rousselet over 5 years
      WillPopScore doesn't need to show a dialog at all. You can do whatever you like with it.
    • Shayan
      Shayan over 3 years
      I believe the way Flutter acts around back button has changed now, instead of closing the app, it now goes back to previous screen. Is that correct?
  • Emre Akcan
    Emre Akcan almost 3 years
    This will only disable the back button