I want to use named parameters in Dart for clarity. How should I handle them?

[Update] New as-of Dart 2.0

In dart 2.0 the required keyword has been added to the language as part of the null-safety update. This means that you get a compiler-enforced non-null value rather than one checked by the analyzer; this makes the null check completely redundant.

This means that this code does effectively the same as the old code below, except that you never have to worry about the assertion throwing as the values for name, effectDuration, and recast cannot be null.

class Ability {
  final String name;
  final Duration effectDuration;
  final bool recast;
  final String? description;

  Ability({
    required this.name,
    this.effectDuration = Duration(seconds: 1),
    this.recast = false,
    this.description,
  });
}

Before Dart 2.0

Yes, there is!

Here's an example:

class Ability {
  final String name;
  final Duration effectDuration;
  final bool recast;
  final String description;

  Ability({
    @required this.name,
    this.effectDuration = new Duration(seconds: 1),
    this.recast = false,
    this.description,
  }): 
    assert(name != null),
    assert(effectDuration != null);
}

You don't have to assert that name is not equal to null, but it might be useful for you.


The meta package provides a @required annotation that is supported by the DartAnalyzer.

Flutter uses this a lot and provides @required directly from import 'package:flutter/foundation.dart'

foo({@required String name}) {...}

foo(); // results in static warning

@required doesn't check if the passed value is null or not, only that a value was actually passed on the call site. To check for null you can also use assert() to check for passed values

class Ability {
  Ability(this.name, this.effectDuration, this.recast) : assert(name != null), assert(effectDuration != null), assert(recast != null);
  final name;
  final effectDuration;
  final recast;            // wait time until next use
  // ...
}