Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't understand @required annotation in this code of Dart

Tags:

flutter

dart

The code is part of this class

   class Category extends StatelessWidget {

      final String name;
      final ColorSwatch color;
      final IconData iconLocation;

And the use of required is this:

    const Category({
    Key key,
    @required this.name,
    @required this.color,
    @required this.iconLocation,
  })  : assert(name != null),
        assert(color != null),
        assert(iconLocation != null),
        super(key: key);

The use of Key key also confuses me.

like image 738
jsdaniell Avatar asked Mar 05 '19 14:03

jsdaniell


People also ask

What is @required in Dart?

The @required annotation indicates that the parameter is a required parameter (i.e an argument needs to be passed to the parameter). You can instead create the function parameters without using the optional parameter syntax which implicitly makes it a required.

What is @required in flutter?

@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.

What is annotation in Dart?

Annotations in Dart An annotation is a form of representing syntactic metadata that can be added to our Dart code; in other words, a way of adding extra information to any component in our code, such as class or a method.

How do you pass NULL values in flutter?

But for handling null-Value from _json you can use HelloWorld(test: _json['test'] ?? "Got Null"); . Passing Got Null because test require a non-nullable String . If you wish to have constructor default value in this case, check _json['x'] provide null or not, then assign on _helloWorld .


1 Answers

The @required annotation indicates that the parameter is a required parameter (i.e an argument needs to be passed to the parameter).
You can instead create the function parameters without using the optional parameter syntax which implicitly makes it a required.

ie This

 Category(
    this.name,
    this.color,
    this.iconLocation,

 )  

Instead of

 Category({
    Key key,
    @required this.name,
    @required this.color,
    @required this.iconLocation,
  })    

Why use the optional parameter syntax together with the @required annotation?

The major benefit of doing it this way is readability! It helps when passing values to your widget fields since you don't have to guess the position of the parameters.

according to Dart's Language tour

Flutter instance creation expressions can get complex, so widget constructors use named parameters exclusively. This makes instance creation expressions easier to read.

like image 105
nonybrighto Avatar answered Oct 09 '22 15:10

nonybrighto