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.
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.
@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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With