mrs.tat
mrs.tat

Reputation: 687

Back button doesn't close the app from home page

I have a flutter app in which when opened it opens the splash screen and then the home page.

when I'm in the home page and I click Android's back button nothing happens since I used this code:

new WillPopScope(
    onWillPop: () async => false,
    child:Directionality(
        textDirection: direction,
        child:...
   )
)

but I want the application to exit if I clicked the back button in Android from the home page.

is there's a way to achieve this?

Upvotes: 1

Views: 935

Answers (1)

Ammar Hussein
Ammar Hussein

Reputation: 6044

This is intended behaviour since WillPopScope overrides the navigation.

You should implement the navigation yourself

example:

Future<bool> _exitApp(BuildContext context) {
  return showDialog(
        context: context,
        child: new AlertDialog(
          title: new Text('Do you want to exit this application?'),
          content: new Text('We hate to see you leave...'),
          actions: <Widget>[
            new FlatButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: new Text('No'),
            ),
            new FlatButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: new Text('Yes'),
            ),
          ],
        ),
      ) ??
      false;
}
new WillPopScope(
    onWillPop: () async => _exitApp(context),
    child:Directionality(
        textDirection: direction,
        child:...
   )
)

Reference.

EDIT to exit the app you can add import 'dart:io'; abd use exit(0) function.

Upvotes: 1

Related Questions