I don't really understand how @required
works. For example I've seen this code:
class Test{
final String x;
Test({
@required this.x
});
factory Test.initial(){
return Test(x: "");
}
}
But what should @required
do here? Seems like it makes an optional parameter a non optional parameter.
As of Dart 2.12, the required
keyword replaces the @required
meta annotation. The following answer has been updated to reflect both this and null safety.
The parameters of a class constructor or function are required by default.
class Test {
final String x;
Test(this.x);
}
You're not allowed to do this:
final value = Test();
// 1 positional argument(s) expected, but 0 found.
You must do this:
final value = Test('hello');
If you surround a parameter with curly braces, though, in addition to becoming a named parameter, it also becomes optional.
Since it's optional, the property must either be nullable like this:
class Test {
final String? x;
Test({this.x});
}
Or it has to have a default value like this:
class Test {
final String? x;
Test({this.x = ''});
}
So now this is ok:
final value = Test();
And so is this:
final value = Test(x: 'hello');
Sometimes a you don't want to allow a parameter to be null
and there is no natural default variable. In that case you can add the add the required
keyword in front of the parameter name:
class Test {
final String x;
Test({required this.x});
}
This is not ok anymore:
final value = Test();
// The named parameter 'x' is required, but there's no corresponding argument.
But this still is:
final value = Test(x: 'hello');