I have this constructor in my class. Now when it's like this, I get
The type parameter icon is annotated with @required
but only named parameters without default value can be annotated with it.
-
const Category(
@required this.name,
@required this.icon,
@required this.color
) : assert(name != null),
assert(icon != null),
assert(color != null);
And when calling the constructor like this:
Category(name: _categoryName, icon: _categoryIcon, color: _categoryColor),
It's an error.
All of this goes away when I surround my constructor arguments with {}.
What does this mean?
In Dart, this is not possible, but there is a way around it. It is called named constructors. Giving your constructors different names allows your class to have many constructors and also to better represent their use cases outside of the class.
There are three types of constructors in Dart: Thus, if a constructor which don't have any parameter then it will be a type of default constructor.
A constructor is a special function of the class that is responsible for initializing the variables of the class. Dart defines a constructor with the same name as that of the class. A constructor is a function and hence can be parameterized. However, unlike a function, constructors cannot have a return type.
{}
are missing to make them named parameters
const Category({
@required this.name,
@required this.icon,
@required this.color
}) : assert(name != null),
assert(icon != null),
assert(color != null);
or just remove @required
Without {}
they are positional parameters which are required anyway.
Category('foo', someIcon, Colors.white)
vs
Category(name: 'foo', icon: someIcon, color: Colors.white)
[]
makes them optional positional parameters.
Positional (non-optional) need to be declared first, optional parameters come at the end.
Optional positional and optional named parameters can not be used together.
Optional parameters (positional and named) can have default values
this.name = 'foo'
Default values need to be compile-time constants.
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