Reputation: 69
I am wondering if anyone knows how to use the device back button to exit the app without going back to any previous pages/routes.
Future<bool> _onBackPressed() {
return showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Are you sure?'),
content: new Text('Do you want to exit an App'),
actions: <Widget>[
new GestureDetector(
onTap: () => Navigator.of(context).pop(false),
child: Text("NO"),
),
SizedBox(height: 16),
new GestureDetector(
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => WelcomeScreen()),
);
},
child: Text("YES"),
),
],
),
) ??
false;
}
Upvotes: 0
Views: 601
Reputation: 1614
To programmatically exit flutter apps, you need to pop the systemNavigator like follow :
SystemNavigator.pop()
SystemNavigator is available after importing Services :
import 'package:flutter/services.dart';
An other method is to use exit(0)
which would terminate the app but is usually not user Interface friendly especially on iOS.
Upvotes: 1
Reputation: 7963
You can exit your app using following ways:
SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop', animated)
exit(0)
SystemNavigator.pop()
Although all three ways works but the preferred way of doing this is to use SystemNavigator.pop()
. The method looks like this:
static Future<void> pop({bool animated}) async {
await SystemChannels.platform.invokeMethod<void>('SystemNavigator.pop', animated);
}
exit(0)
is not a recommended way as it immediately terminates the process running in dart VM and looks a bit like your app is crashed.
Upvotes: 0