Consider the following piece of code:
class Person {
String id;
String name;
ConnectionFactory connectionFactory;
// What is this constructor doing?
Person({this.connectionFactory: _newDBConnection});
}
If you precede a constructor's argument with this
, the corresponding field will be automatically initialized, but why {...}
?
the
this. connectionFactory
inis called Automatic Class Member Variable Initialization. See this example
This makes the argument a named optional argument.
When you instantiate a
Person
you can{}
the argument would be mandatory[]
the argument would be an optional positional argumentNamed optional parameters are very convenient for boolean arguments (but of course for other cases too).
There is a specific order in which these argument types can be used:
Note that positional and named optional arguments use a different delimiter for the default value. The named requires:
but the positional requires=
. The language designers argue that the colon fits better with the Map literal syntax (I would at least have used the same delimiter for both).=
is supported as delimiter since Dart 2 and preferred according to the style guide while:
is still supporzed.See also: