Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors in dart [duplicate]

Tags:

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?

like image 957
MAA Avatar asked May 19 '18 18:05

MAA


People also ask

Can I have multiple constructors in Dart?

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.

How many constructors can a class have in Dart?

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.

What does a constructor do in Dart?

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.


1 Answers

{} 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.

like image 196
Günter Zöchbauer Avatar answered Sep 21 '22 16:09

Günter Zöchbauer