Flutter: @required keyword

╄→гoц情女王★ 提交于 2019-12-22 10:36:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!