๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Dart Named Parameters

Named parameters are function inputs that a call gives by name. Curly braces in the definition mark parameters as named.

Calling by name in any order

The call gives city first and name second, the swap of the definition order. The print still puts the name before the city.

void greet({String name = 'guest', String city = 'York'}) {
  print('$name from $city');
}

void main() {
  greet(city: 'Rome', name: 'Ana');
}

A required named parameter

name carries required, so both calls give it. level has a default of 1, and only the second call changes it.

void enroll({required String name, int level = 1}) {
  print('$name at level $level');
}

void main() {
  enroll(name: 'Bo');
  enroll(level: 3, name: 'Cy');
}

A default value fills in

The first call gives no names, so both defaults fill in. The second call gives both names and its own values win.

void ticket({String kind = 'adult', int price = 10}) {
  print('$kind: $price');
}

void main() {
  ticket();
  ticket(kind: 'child', price: 5);
}

Leaving out a required name fails

The call gives no name at all, and name is required. The compiler stops at the call and names the missing parameter.

void enroll({required String name}) {
  print(name);
}

void main() {
  enroll();
}

Example

String label({required String name, int score = 0}) {
  return '$name scored $score';
}

void main() {
  print(label(name: 'Ana', score: 90));
  print(label(score: 75, name: 'Bo'));
  print(label(name: 'Cy'));
}

Key points

  • Curly braces in a definition mark its parameters as named.
  • A call gives each named value with its name, a colon, and the value.
  • Named values at a call can sit in any order.
  • The word required marks a named parameter that every call must give.
  • A default value sits after = in the definition.
  • A default value fills in when a call leaves that name out.

In this example, label takes a required name and a score with a default of 0. The first call gives both names and the print shows Ana with 90. The second call swaps the order and the print still shows Bo with 75. The third call gives only the name, so the default fills the score in as 0.

Note

Leaving out a required named parameter is a compile error, not a null value.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What does required mark in a definition?