Dart Easy · Lesson 1 · On the house

Named and optional parameters

Positional optional [ ], named { }, required, and default values. Lesson 1 is free — on the house.

Lessons · Dart Easy · Lesson 1 of 10 · On the house

Named and optional parameters

Positional optional [ ], named { }, required, and default values.

Illustration for Dart
Lesson 1 is on the house.

Wrap trailing positional parameters in [ ] to make them optional: String greet(String name, [String? title]). Callers may omit them, and an omitted nullable one is null.

Named parameters go in { } and are passed by name: box(width: 2, height: 3). Order at the call site does not matter, which makes calls with many flags readable.

A named parameter is optional unless marked required. Non-nullable optional parameters need a default: {int retries = 3}. Defaults must be compile-time constants.

Mixing is limited: a function can have optional positional or named parameters, not both. Required positional parameters always come first.

Misses: forgetting required on a non-nullable named parameter with no default (compile error), and passing a named argument positionally.

named params

String box({required int width, int height = 1}) =>
    '${width}x$height';

String greet(String name, [String? title]) =>
    title == null ? 'Hi $name' : 'Hi $title $name';

void main() {
  print(box(width: 4));
  print(box(height: 2, width: 3));
  print(greet('Ada'));
  print(greet('Ada', 'Dr'));
}
Match this when you type.

Quiz

What does box(width: 4) return?

Quiz

How do you mark a named parameter that callers must pass?

Quiz

Which brackets declare optional positional parameters?

Quiz

Can one function mix optional positional and named parameters?

Check

Match the still for: Named and optional parameters.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.