Optional parameters
Optional parameters can be either named or positional, but not both.
Named parameters
When calling a function, you can specify named parameters usingparamName: value
. For example:
enableFlags(bold: true, hidden: false);
When defining a function, use{param1, param2, …}
to specify named parameters:
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold, bool hidden}) {...}
Although named parameters are a kind of optional parameter,you can annotate them with @required to indicatethat the parameter is mandatory —that users must provide a value for the parameter.For example:
- const Scrollbar({Key key, @required Widget child})
If someone tries to create a Scrollbar
without specifying the child
argument,then the analyzer reports an issue.
To use the @required annotation,depend on the meta package and import package:meta/meta.dart
.
Positional parameters
Wrapping a set of function parameters in []
marks them as optionalpositional parameters:
String say(String from, String msg, [String device]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
return result;
}
Here’s an example of calling this function without the optionalparameter:
assert(say('Bob', 'Howdy') == 'Bob says Howdy');
And here’s an example of calling this function with the third parameter:
assert(say('Bob', 'Howdy', 'smoke signal') ==
'Bob says Howdy with a smoke signal');
Default parameter values
Your function can use =
to define default values for both named and positionalparameters. The default values must be compile-time constants.If no default value is provided, the default value is null
.
Here’s an example of setting default values for named parameters:
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold = false, bool hidden = false}) {...}
// bold will be true; hidden will be false.
enableFlags(bold: true);
Deprecation note: Old code might use a colon (:
) instead of =
to set default values of named parameters. The reason is that originally, only :
was supported for named parameters. That support might be deprecated, so we recommend that you use =
to specify default values.
The next example shows how to set default values for positional parameters:
String say(String from, String msg,
[String device = 'carrier pigeon', String mood]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
if (mood != null) {
result = '$result (in a $mood mood)';
}
return result;
}
assert(say('Bob', 'Howdy') ==
'Bob says Howdy with a carrier pigeon');
You can also pass lists or maps as default values.The following example defines a function, doStuff()
,that specifies a default list for the list
parameter and a default map for the gifts
parameter.
void doStuff(
{List<int> list = const [1, 2, 3],
Map<String, String> gifts = const {
'first': 'paper',
'second': 'cotton',
'third': 'leather'
}}) {
print('list: $list');
print('gifts: $gifts');
}