Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 61 ยท Functions

Positional, Named and Optional Parameters

Learn Dart function parameters: required positional, optional positional in brackets, named parameters in braces, default values and the required keyword.

Dart has an unusually rich parameter system. A parameter can be positional (identified by its place in the call) or named (identified by its label), and either kind can be required or optional. Named parameters are the reason Flutter code reads like Text('Hi', style: ..., maxLines: 2): each argument says what it is.

This lesson explains all four combinations, how defaults work and how the required keyword fits in. If you need a refresher on declaring a function, see Functions. The Dart code is read-only; the runnable TypeScript stand-ins use an options object, which is the closest equivalent in TypeScript.

Required positional parameters

The simplest parameters are required and positional. The caller must pass exactly one argument for each, in the same order.

DART
String fullName(String first, String last) => '$first $last';

void main() {
  print(fullName('Ada', 'Lovelace'));
  // fullName('Ada');            // error: too few positional arguments
  // fullName('Ada', 'L', 'x');  // error: too many positional arguments
}

Use these when there are one to three parameters and their order is obvious. With more, calls become hard to read: what does createUser('Ada', 36, true, false) mean?

Optional positional parameters

Wrap parameters in square brackets to make them optional. They must come after all required positional parameters. If the caller leaves one out, it is null unless you give it a default value.

DART
String greet(String name, [String greeting = 'Hello', String? suffix]) {
  final base = '$greeting, $name';
  return suffix == null ? base : '$base$suffix';
}

void main() {
  print(greet('Ada'));                 // Hello, Ada
  print(greet('Ada', 'Welcome'));      // Welcome, Ada
  print(greet('Ada', 'Welcome', '!')); // Welcome, Ada!
}

Here greeting has the default 'Hello'. suffix has no default, so its type must be nullable (String?); otherwise Dart rejects the declaration, since the missing argument would leave it without a value.

The catch: to pass the third argument you must also pass the second. Optional positionals are filled strictly from left to right. If that bothers you, named parameters are the better tool.

TypeScript Optional positional parameters (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Named parameters

Put parameters in curly braces to make them named. Callers write the name, a colon and the value, in any order:

DART
void createUser({String? name, int age = 18, bool admin = false}) {
  print('$name, $age, admin: $admin');
}

void main() {
  createUser(name: 'Ada', age: 36);
  createUser(admin: true, name: 'Grace');
  createUser();
}
TEXT
Ada, 36, admin: false
Grace, 18, admin: true
null, 18, admin: false

Named parameters are optional by default. An omitted one takes its default value, or null when it has none, which is why name is typed String? above. The call site is self-describing: admin: true explains itself in a way that a bare true never would.

Named arguments are matched by name, so their order does not matter. In a call they may appear before or after positional arguments.

The required keyword

If a named parameter must always be provided, mark it required. The analyzer then flags a call that forgets it, and you can use a non-nullable type without a default:

DART
void createUser({required String name, required String email, int age = 18}) {
  print('$name <$email>, $age');
}

void main() {
  createUser(name: 'Ada', email: '[email protected]');
  // createUser(name: 'Ada'); // error: the named parameter 'email' is required
}

A required named parameter is the best of both worlds: it is clear at the call site and it cannot be forgotten.

flowchart TD
    P["Which parameter style?"] --> Q1{"Always needed and<br/>order is obvious?"}
    Q1 -->|"yes"| R["Required positional"]
    Q1 -->|"no"| Q2{"Several optional values<br/>or flags?"}
    Q2 -->|"yes"| N["Named, with required<br/>for the mandatory ones"]
    Q2 -->|"no"| O["Optional positional in brackets"]

A rule of thumb for choosing between the parameter styles.

TypeScript Named parameters with an options object (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Mixing positional and named parameters

A function can have required positional parameters followed by either optional positionals or named parameters, but not both optional kinds at once:

DART
// Valid: required positional + named
Future<String> fetch(String url, {int retries = 3, Duration? timeout}) async {
  return 'GET $url (retries: $retries)';
}

// Invalid: [ ] and { } together
// void bad([int a = 1], {int b = 2}) {}

In a declaration, the order is always: required positional, then one group of optional positional or named. A common design is one or two required positional values (what the function works on) followed by named options (how it should behave), like fetch(url, retries: 5).

Default values

A default must be a compile-time constant: a literal, a const value or a constant expression.

DART
void log(String message, {String level = 'INFO', int indent = 0}) {
  print('${' ' * indent}[$level] $message');
}

// Not allowed: the default must be constant
// void bad({DateTime when = DateTime.now()}) {}

When you need a default that is computed when the function runs, make the parameter nullable and fill it in inside the body:

DART
void stamp(String text, {DateTime? when}) {
  final time = when ?? DateTime.now();
  print('$time: $text');
}

The ?? operator returns its right side when the left side is null. You can also write when ??= DateTime.now();.

Do not give a default to a parameter that is also required. A required parameter is never missing, so the default could never apply, and Dart reports it as an error.

Parameters that initialize fields

In classes, a parameter written as this.name copies its argument straight into the field of the same name. It works with every parameter kind you learned here, and you will use it constantly in Constructors:

DART
class User {
  final String name;
  final int age;
  User({required this.name, this.age = 18});
}

Optional versus nullable

These two ideas are independent. A parameter is optional if the caller may omit it. A parameter is nullable if its type allows null. {required String? note} must be passed, but may be null. {String note = ''} may be omitted, and can never be null. Keeping the two apart avoids a lot of confusion.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you declare a named parameter that must be provided?

    Named parameters go inside curly braces, and the required keyword makes them mandatory.
  2. 2. What value does an omitted optional parameter without a default have?

    An omitted argument without a default becomes null, which is why such a parameter needs a nullable type like String?.
  3. 3. Which declaration is valid?

    Required positional parameters come first, followed by a single group of optional positional or named parameters. Optional positional and named groups cannot be mixed, and a second bracket group is not allowed.
  4. 4. What kind of expression can a parameter default be?

    Defaults must be constants. For a computed default, use a nullable parameter and the ?? operator inside the body.

Summary

  • Required positional parameters are matched by order; add [ ] for optional positionals.
  • { } creates named parameters, passed as name: value in any order.
  • Mark mandatory named parameters required; optional ones need a default or a nullable type.
  • You can combine required positionals with either optional positionals or named parameters, not both.
  • Defaults must be compile-time constants; compute others inside the body with ??.
  • this.field parameters assign fields directly in constructors.

Next: first-class functions, closures and typedefs.