Home > Back-end >  Can't add element to List in flutter
Can't add element to List in flutter

Time:07-04

how can I add the element first to my List deckList?

deckList.add(first); is under lighted red with the note: "The name of a constructor must match the name of the enclosing class."

import 'dart:ui';

class _GamingCard{
  int ?value1;
  int ?value2;
  String ?name;
  String ?type;
  Image ?image;

  _GamingCard(this.value1,this.value2,this.name,this.type,this.name);
}

class _DeckofCards{
  List<_GamingCard> ?deckList = List<_GamingCard>.empty(growable: true);

  _GamingCard first = _GamingCard(1,10,'ace','heart',null);
  _GamingCard second = _GamingCard(1,10,'ace','cross',null);
  deckList.add(first);
}

CodePudding user response:

The warring is coming from null-safety. If you like to insert data firstly, you can use constructor or provide inside list.

It can be like

 _DeckofCards() {
    deckList.add(first);
  }

Or just add while declaring list

class _DeckofCards {
  _GamingCard first = _GamingCard(1, 10, 'ace', 'heart', null);
  _GamingCard second = _GamingCard(1, 10, 'ace', 'cross', null);

  late List<_GamingCard> deckList = [first];
}

More about List on dart

One more thing, on your _GamingCard constructor, you didn't include image params, also It would be better to use named constructor for this.

More about using-constructors

  • Related