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;
requiredmakes 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 asname: value, in any order. They are optional, so each needs a default, a nullable type, or the wordrequired. - 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).