0

What codes should I use to go back to the page with the flutter android back button? I looked inside youtube, especially on Stackoverflow, but I couldn't get any results.

can
  • 41
  • 1
  • 1
  • 3
  • Does this answer your question? [catch Android back button event on Flutter](https://stackoverflow.com/questions/50452710/catch-android-back-button-event-on-flutter) – Md. Yeasin Sheikh Jan 03 '22 at 13:23
  • Do you mean go back programmatically? Use Navigator.of(context).pop() to go to previous route. Use Navigator.of(context).maybePop() to closely simulate pressing back button. This is better because it makes sure you can go back before going back and use any WillPopScopes of the parent if specified. – Afridi Kayal Jan 03 '22 at 13:44
  • And if you want to close whole app through back button of android in Flutter then you can use exit(0) – Developer Jan 03 '22 at 13:58

2 Answers2

0

You can use WillPopScope

Here is example code:

class MyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // This function will handle back button
        // When true, it's can back to previous page
        // when false, back button will do nothing
        return true;
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter WillPopScope demo'),
        ),
        body: Center(
          child: Text('Hello world')
        ),
      ),
    );
  }
}
Muhammad Andika
  • 116
  • 1
  • 5
0
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());
Yunus Kocatas
  • 286
  • 2
  • 9