Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Basics of Dart  ›  Lesson

DartPad — Your First Dart Program

Dart Pad 12 minDartPad runs Dart and Flutter code in the browser, and every Dart program starts running at the top-level main function.

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');
}
  • void says main gives nothing back.
  • print writes 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.

Reading a snippet from main outwardStep 1 of 4
  1. 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.

quick drill

Which function does Dart run first when a program starts?

quick drill

A file declares void tip() { print('Mist the fern'); } and a main that prints only 'Sprout'. What appears in the console?

quick drill

What is wrong with print('Water the cactus') inside main, with nothing after the closing parenthesis?

quick drill

Which statement about DartPad is true?

Remember

  • Dart starts at main(); nothing else runs unless something calls it.
  • Read a snippet by finding main and following its calls outward.
  • Trap: a declared function is not a called function, and every statement needs ;.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhere does it start?

Write a tiny Dart program for Sprout that prints two lines: the app's name and one plant that needs water today. Then explain where Dart starts running your code and what would happen if you renamed main to start.