Skip to the workspace
Pebellslearn by building
Basics of Dart  ›  Lesson

Functions and Parameters

Functions 12 minDart functions take positional parameters by place and named parameters by name, where named parameters are optional unless marked required, and single-expression bodies can use arrow syntax.

flutter / Functions and Parameters

Explore each scene at your own pace.

01 · The rule

The rule

Functions and Parameters

Sprout builds the same kind of message over and over: "Fern: water every 3 days". A function wraps that logic once. Dart's parameter system then lets each call read almost like a sentence, if you choose between positional and named parameters well.

The rule

Positional by place, named by name; required makes a name mandatory.

String reminder(String plant, {int days = 7, bool outdoors = false}) {
  final where = outdoors ? 'outside' : 'inside';
  return '$plant ($where): every $days days';
}

reminder('Fern', days: 3);   // 'Fern (inside): every 3 days'
  • Positional parameters, like plant, are matched by their order in the call.
  • Named parameters sit inside { } and are passed as name: value, in any order. They are optional, so each needs a default, a nullable type, or the word required.
  • Optional positional parameters sit inside [ ]: void log(String msg, [String? tag]).

A function whose body is one expression can use the arrow:

bool isDue(int daysSince, int every) => daysSince >= every;

=> expr is short for { return expr; }. Functions are values too, so you can pass one to another: plants.where((p) => p.outdoors).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.