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()));
},
),
),
);
}
}
Author by
Darwish Al-Neyadi
Updated on December 06, 2022Comments
-
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 over 5 yearsWillPopScore doesn't need to show a dialog at all. You can do whatever you like with it.
-
Shayan over 3 yearsI 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 almost 3 yearsThis will only disable the back button