TExcelTAD
Home › Dart › Named & Optional Parameters

Named & Optional Parameters

Dart functions support three kinds of parameters: required positional, optional positional (in [ ]) and named (in { }). Used well, they make call sites read like documentation — sendEmail(to: user, subject: 'Hi', urgent: true) is far clearer than sendEmail(user, 'Hi', true).

Overview

Kind Declaration Call Nullable or default needed?
Required positional f(int a) f(1) No
Optional positional f([int a = 0]) f() or f(1) Yes
Named (optional) f({int a = 0}) f() or f(a: 1) Yes
Named (required) f({required int a}) f(a: 1) No

A function may combine required positional parameters with either optional positional or named parameters, but not both.

Optional positional parameters

Wrap them in square brackets. They must come last, and they need a default value or a nullable type:

dart · try it yourself
String formatPrice(double amount, [String currency = 'VND', int? decimals]) {
  final digits = decimals ?? (currency == 'VND' ? 0 : 2);
  return '${amount.toStringAsFixed(digits)} $currency';
}

void main() {
  print(formatPrice(45000));
  print(formatPrice(12.5, 'USD'));
  print(formatPrice(12.5, 'USD', 3));
}
45000 VND
12.50 USD
12.500 USD

Optional positional parameters are best for one or two "obvious" extras. Beyond that, callers can't tell what f(1, true, false) means — use named parameters.

Named parameters

Wrap them in curly braces. Callers pass them as name: value, in any order:

dart · try it yourself
String makeTag(String text, {String color = 'gray', bool bold = false, int? size}) {
  final parts = [
    'color=$color',
    if (bold) 'bold',
    if (size != null) 'size=$size',
  ];
  return '[$text | ${parts.join(', ')}]';
}

void main() {
  print(makeTag('Draft'));
  print(makeTag('Sale', bold: true, color: 'red'));
  print(makeTag('Tiny', size: 8));
}
[Draft | color=gray]
[Sale | color=red, bold]
[Tiny | color=gray, size=8]

Required named parameters

required makes a named parameter mandatory. It can then be non-nullable with no default:

dart · try it yourself
class Booking {
  final String guest;
  final int nights;
  final bool breakfast;

  Booking({required this.guest, required this.nights, this.breakfast = false});

  @override
  String toString() => '$guest: $nights night(s)${breakfast ? ' + breakfast' : ''}';
}

void main() {
  print(Booking(guest: 'Khoa', nights: 2));
  print(Booking(nights: 1, guest: 'Yen', breakfast: true));
}
Khoa: 2 night(s)
Yen: 1 night(s) + breakfast

Forget a required argument and the compiler stops you:

dart · try it yourself
void connect({required String host, int port = 80}) {
  print('$host:$port');
}

void main() {
  connect(port: 8080);
}
example.dart:6:10: Error: Required named parameter 'host' must be provided.
  connect(port: 8080);
         ^
example.dart:1:6: Context: Found this candidate, but the arguments don't match.
void connect({required String host, int port = 80}) {
     ^^^^^^^
Error: AOT compilation failed
Bad state: Generating AOT kernel dill failed!

Default values must be constant

Defaults are compile-time constants. To use a computed default, make the parameter nullable and fill it in the body:

dart
// Not allowed: List<String> tags = []  (a non-const default)
void post(String text, {List<String> tags = const []}) { }

// Computed default
void log(String msg, {DateTime? at}) {
  final time = at ?? DateTime.now();
  print('$time $msg');
}

Named arguments anywhere (Dart 2.17+)

Named arguments may appear before, between or after positional ones at the call site. This is handy when a long closure is the positional argument:

dart · try it yourself
void retry(void Function(int attempt) action, {int times = 2}) {
  for (var i = 1; i <= times; i++) {
    action(i);
  }
}

void main() {
  retry(times: 3, (attempt) {
    print('attempt $attempt');
  });
}
attempt 1
attempt 2
attempt 3

Choosing the right kind

  • Required positional — the essential inputs whose meaning is obvious: max(a, b), distance(p, q).
  • Named — anything optional, boolean flags, and configuration. Almost all Flutter widget parameters are named.
  • required named — mandatory values where a label improves readability: Rect(width: 3, height: 4).
  • Optional positional — rare; a single trailing optional value like substring(start, [end]).

Tip: Boolean parameters should almost always be named. save(true) is a mystery; save(overwrite: true) is not.

Test yourself

How do you declare a named parameter that callers must always pass?

  1. {int! count}
  2. {required int count}
  3. [int count]
  4. {final int count}

Which declaration has an optional positional parameter?

  1. f(int a, {int b = 0})
  2. f(int a, [int b = 0])
  3. f(int a, int? b)
  4. f({int a})

Why is List<String> tags = [] not allowed as a default value?

  1. Lists can't be parameters
  2. Default values must be compile-time constants
  3. Named parameters can't be lists
  4. It is allowed