Can't define constructor with optional parameters Dart
269
You can't have Positional
optional parameters []
and Named
optional parameters {}
at the same time. Have a look at this.
If you want too keep your Named
parameters you can do the following.
class Artists_Showroom extends StatefulWidget {
const Artists_Showroom({
Key key,
@required this.lista,
@required this.database,
@required this.artistaCorrente,
this.color,
}) : super(key: key);
final List<Artista> lista;
final Artista artistaCorrente;
final Database database;
final Color color;
}
Author by
Finley Adams
Updated on January 01, 2023Comments
-
Finley Adams over 1 year
I can't define this constructor :
class Artists_Showroom extends StatefulWidget { Artists_Showroom( //error 1 here {Key key, @required this.lista, @required this.database, @required this.artistaCorrente, [this.color = null]}). //error 2 here on first square brachet : super(key: key); final List<Artista> lista; final Artista artistaCorrente; final Database database; final Color color;
Error 1 :
All final variables must be initialized, but 'color' isn't. Try adding an initializer for the field.
Error 2 :
Expected to find '}'. Expected an identifier.
It worked until now because I need to add an optional parameter (in this case it's a color). I just never used optional parameters so I don't know how to declare them.
I did some researches and tried different solutions from StackOverflow but no one working.
-
Finley Adams over 2 yearsOk but this time I need to pass "null" value each time I call the constructor right?
-
quoci over 2 yearsNo you don't. If you don't pass anything then it is implicity null. Just call it like
Artis_Showroom(lista: lista, database:database, artistaCorrente: artistaCorrente)
and the color is thennull
. -
Finley Adams over 2 yearsPerfect explanation, I don't know why dart docs aren't clear like you