简体   繁体   中英

Can't define constructor with optional parameters Dart

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM