问题
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.
回答1:
@required is needed when you have more than 1 named parameters and you want some of the parameters to be mandatory, you annotate it using @required.
Example
class Test {
final String a; // say a is mandatory
final String b;
final String c;
final String d;
Test({
@required this.a, // annotate it using required
this.b,
this.c,
this.d,
});
}
回答2:
@required is an annotation that will create a warning for you to remember that the named parameter is necessary for the class to work as expected. It will not create compile errors, at least for what I know.
回答3:
@required bounds you to pass @required marked arguments while creating object of Class. For example, while showing a dialog, you'd mark context as required since, you cannot show dialog without having a valid context. But, you should not overuse it.
来源:https://stackoverflow.com/questions/54181838/flutter-required-keyword