Flutter how to programmatically exit the app
Answers are provided already but please don't just copy paste those into your code base without knowing what you are doing:
If you use SystemChannels.platform.invokeMethod('SystemNavigator.pop');
note that doc is clearly mentioning:
Instructs the system navigator to remove this activity from the stack and return to the previous activity.
On iOS, calls to this method are ignored because Apple's human interface guidelines state that applications should not exit themselves.
You can use exit(0)
. And that will terminate the Dart VM process immediately with the given exit code. But remember that doc says:
This does not wait for any asynchronous operations to terminate. Using exit is therefore very likely to lose data.
Anyway the doc also did note SystemChannels.platform.invokeMethod('SystemNavigator.pop');
:
This method should be preferred over calling dart:io's exit method, as the latter may cause the underlying platform to act as if the application had crashed.
So, keep remember what you are doing.
Below worked perfectly with me in both Android
and iOS
, I used exit(0)
from dart:io
import 'dart:io';
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new ... (...),
floatingActionButton: new FloatingActionButton(
onPressed: ()=> exit(0),
tooltip: 'Close app',
child: new Icon(Icons.close),
),
);
}
UPDATE Jan 2019 Preferable solution is:
SystemChannels.platform.invokeMethod('SystemNavigator.pop');
As described here
For iOS
SystemNavigator.pop()
: Does NOT WORK
exit(0)
: Works but Apple may SUSPEND YOUR APP
Please see:
https://developer.apple.com/library/archive/qa/qa1561/_index.html
For Android
SystemNavigator.pop()
: Works and is the RECOMMENDED way of exiting the app.
exit(0)
: Also works but it's NOT RECOMMENDED as it terminates the Dart VM process immediately and user may think that the app just got crashed.
Please see:
https://api.flutter.dev/flutter/services/SystemNavigator/pop.html
You can do this with SystemNavigator.pop()
.