concept main() in category dart

appears as: main()
Dart in Action

This is an excerpt from Manning's book Dart in Action.

Each Dart script has a single entry-point function called main() that is the first function executed by the Dart VM. Thus you can rely on all code that defines an application when the main function is called; you can’t define and execute a function within running code as you can with JavaScript—there is no eval() or other monkey-patching of executing code. This single feature helps you write Dart applications that fit the single-page application architecture, because you can be sure your code will execute as a single, known unit of code. The Dart VM uses this feature to improve application start-up time, using heap snapshots to load apps much more quickly than the equivalent JavaScript application.

The application/dart tag loads the initial .dart script, which in turn loads all other files required by part and noncore import statements. Once the entire app is loaded and parsed by the Dart VM, the main() function is called. This ability to parse the entire application when it’s loaded provides a large performance gain over JavaScript applications. This gain doesn’t come without cost, however. Unlike JavaScript, you can’t modify Dart code dynamically at runtime—a practice known as monkey-patching.

All Dart applications start with a main() function, which executes automatically once all the code has been loaded—and DartExpense is no exception. When a Dart app starts running, it uses the code started by main() to build a UI and wire up event handlers, such as button on-click events. Once that code finishes executing, the app is still running, but in a passive state, waiting for the browser to trigger events in the app.

Of course, it’s better to see this in code, so the following listing shows the DartExpense.dart entry point file with the main() function.

Listing 10.2. DartExpense.dart main() function

Once the UI is built and the first view is attached, main() finishes. The application goes into its wait-event loop phase, during which the user can begin to interact with the application by clicking the Add button to create a new expense or the Edit button to edit existing expenses.