How to use a List as member variable in Flutter?

Issue

I tried to define a class, which contains a List of a specific item-object, which will be populated within Constructor and will also receive new items at a later time:

class Repository {

  final List<Voting> _items = List<Voting>();

  Repository() {
    _items.add(Voting(1, "xyz", 0));
  }

  List<Voting> fetchItems() {
    return _items;
  }

}

However, Flutter is complaining:

The default ‘List’ constructor isn’t available when null safety is
enabled.

How to do?

Solution

Try this:

final List<Voting> _items = <Voting>[];

instead of

final List<Voting> _items = List<Voting>();

Answered By – kforjan

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *