DartPad — Your First Dart Program
Throughout this course you will build the ideas behind Sprout, a small app that reminds you when each houseplant needs water. Before any screens exist, you need to be able to try a line of Dart in seconds. DartPad, at dartpad.dev, lets you do that in a browser tab with nothing installed.
The rule
Dart starts at
main(); everything else waits to be called.
A Dart program is a file of declarations: functions, classes, variables. None of them run on their own. When the program starts, Dart looks for one top-level function named main and runs its body from top to bottom.
void main() {
print('Sprout');
print('Water the fern today');
}voidsaysmaingives nothing back.printwrites a line to the console, which DartPad shows beside your code.- Every statement ends with a semicolon. Leave one out and DartPad underlines the line before you even press Run.
DartPad can also run Flutter. If the code imports package:flutter/material.dart and calls runApp, the right-hand panel shows a live app instead of plain text. It supports only a chosen set of popular packages, so it is a sketchpad, not a place to build the whole project.
The shortcut
When you read any Dart snippet, find main first and trace outward. Whatever main calls runs; whatever it never mentions is just waiting on the shelf.
Spot main
Scan for
void main(). That is line one of the story, even if it sits at the bottom of the file.
A common slip is expecting a function to run because it is defined. Declaring is not calling: only main is called for you.
Drills
Answer fast — trust the rule.
Which function does Dart run first when a program starts?
A file declares void tip() { print('Mist the fern'); } and a main that prints only 'Sprout'. What appears in the console?
What is wrong with print('Water the cactus') inside main, with nothing after the closing parenthesis?
Which statement about DartPad is true?
Remember
- Dart starts at
main(); nothing else runs unless something calls it. - Read a snippet by finding
mainand following its calls outward. - Trap: a declared function is not a called function, and every statement needs
;.
