官术网_书友最值得收藏!

Exiting from an app

A Dart program starts its execution from the main() function in one thread (or isolate) in the Dart VM. The Dart VM by design always starts up single threaded. The program can end in three different ways:

  • It can end in a normal way by executing the last statement from main() and returning the exit code with the value 0, which means success
  • It can terminate abnormally with a runtime exception, returning exit code different from 0, such as 255 in the case of an unhandled exception
  • It can wait in an event loop for user interaction (such as in the browser or a web server waiting for requests), and then terminate when the browser is closed or another app is started in the same browser tab

However, how can we exit the app from the code itself? This can be useful, for example, in a server-side VM app with some Futures that may or may not return.

How to do it...

The first possibility is to use the exit(int code) top-level function from dart:io, as in exit_app.dart, to stop the app from an endless loop or at a certain condition, and return the exit code:

import 'dart:io';

void main() {
  var message = "Dart is fun!";
  int i = 0;
  while (true) {
    print(message);
    i++;
    if (i == 10) {
      print("That's enough!");
 exit(10);
    }
  }
}

You can also set the exit code value with the property exitCode, as shown in the following code:

exitCode = 10;
// … other code can be execut
ed
exit(exitCode);

How it works...

The exit (code) function will terminate the running Dart VM process and return the integer code as the exit value to the parent process or OS environment, indicating the success, failure, or other exit state of the program. You can choose the value of the code; there is a convention to use 0 for success, 1 for warnings, and 2 for errors. Another convention is zero for success, non-zero for failure, and a program returning a warning for a successful exit because it naturally reached its end. A concrete example is the dartanalyzer program, which returns 0 if the code generates warnings.

Setting the exit code is preferred because the program can still run to its natural completion, or some cleanup or finalizing code (such as closing a file or database connection) can be run before exit(exitCode) ends the app. It is also good practice to start main() with exitCode = 0, presuming success as the normal ending state.

Tip

What exit codes mean is platform-specific; you will not run into cross-platform issues if you use exit codes in the range of 0–127.

主站蜘蛛池模板: 科技| 建平县| 呼伦贝尔市| 嘉善县| 淄博市| 鄂州市| 铁岭市| 兖州市| 平武县| 富源县| 邢台市| 东台市| 和田县| 阿鲁科尔沁旗| 比如县| 蓬溪县| 莱州市| 胶南市| 虎林市| 菏泽市| 新竹县| 德格县| 新昌县| 大方县| 合江县| 江阴市| 宁蒗| 荔浦县| 雅江县| 三明市| 沧州市| 宝鸡市| 北碚区| 武隆县| 武城县| 静宁县| 余江县| 青阳县| 探索| 肇东市| 武夷山市|