Flutter how to programmatically exit the app

2020-01-24 12:34发布

How can I programmatically close a Flutter application. I've tried popping the only screen but that results in a black screen.

标签: flutter dart
4条回答
Anthone
2楼-- · 2020-01-24 13:06

For iOS

SystemNavigator.pop(): Does NOT WORK

exit(0): Works but Apple may SUSPEND YOUR APP because it's against Apple Human Interface guidelines to exit the app programmatically.


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.

查看更多
Luminary・发光体
3楼-- · 2020-01-24 13:18

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.

查看更多
甜甜的少女心
4楼-- · 2020-01-24 13:24

You can do this with SystemNavigator.pop().

查看更多
\"骚年 ilove
5楼-- · 2020-01-24 13:25

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

查看更多
登录 后发表回答