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.