Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch Android back button event on Flutter

Is there any way I can catch the onBackPressed event from Android back button?

I've tried the WillPopScope but my onWillPop function only triggered when I tap on the Material back arrow button

I put it like this:

class MyView extends StatelessWidget{  Widget build(BuildContext context) {      return new WillPopScope(       onWillPop: () async {         debugPrint("Will pop");         return true;       },       child: ScopedModel<AppModel>(       model: new AppModel(),       child: new Scaffold(...... 

I need to catch it because somehow my screen behaved incorrectly when it came to back button pressed, it pops the screen and the screen below it, but somehow, using material back arrow button works normal.

Update:

The code works, my problem was not in the pop of this screen, but on the previous screen, I use 2 MaterialApp widgets, and somehow it gave a weird behavior.

like image 924
Rizky Andriawan Avatar asked May 21 '18 16:05

Rizky Andriawan


People also ask

How do you get the back button event in Flutter?

By tapping the Android back-button (or the "pop" button) each square turns blue, one by one. Only when all squares are blue, tapping the back-button once more will return to the previous screen.


2 Answers

In order to prevent navigating back WillPopScope is the correct way and should be used as follow:

class Page2 extends StatelessWidget {   @override   Widget build(BuildContext context) {     return new WillPopScope(       child: new Scaffold(         appBar: new AppBar(           title: new Text('Page 2'),         ),         body: new Center(           child: new Text('PAGE 2'),         ),       ),       onWillPop: () async {         return false;       },     );   } }  Future<T> pushPage<T>(BuildContext context, Widget page) {   return Navigator.of(context)       .push<T>(MaterialPageRoute(builder: (context) => page)); } 

Can call the page like:

pushPage(context, Page2()); 
like image 108
Arnold Parge Avatar answered Oct 03 '22 02:10

Arnold Parge


This is should be helpful.

@override Widget build(BuildContext context) {   return WillPopScope(     onWillPop: () {       _moveToScreen2(context, );     },     child: Scaffold(       key: _scaffoldKey,       appBar: AppBar(         leading: IconButton(             icon: Icon(Icons.arrow_back),             onPressed: () {               _moveToScreen2(context);             }),         title: Text("Screen 1"),       ),     ),   ); }  /** * This is probably too thin to be in its own method - consider using * `Navigator.pushReplacementNamed(context, "screen2")` directly */ void _moveToScreen2(BuildContext context) =>     Navigator.pushReplacementNamed(context, "screen2"); 
like image 36
Mitch Avatar answered Oct 03 '22 04:10

Mitch