0
class CatalogModel {
  static List<Item> items;
  static Item getById(int id) =>
      items.firstWhere((element) => element.id == id, orElse: null);
  static Item getByPosition(int pos) => items[pos];
}

I'm trying to create the class with a static list 'items', where I'm getting the following error:

The non-nullable variable 'items' must be initialized. Try adding an initializer expression.

What should I do?

nvoigt
  • 75,013
  • 26
  • 93
  • 142

2 Answers2

0

Either hardCode the initial value or create a constructor so the user can pass it in :

Option 1

class CatalogModel {
  static List<Item> items=[];
  static Item getById(int id) =>
      items.firstWhere((element) => element.id == id, orElse: null);
  static Item getByPosition(int pos) => items[pos];
}

Option 2

class CatalogModel {
  final List<Item> items;
const CatalogModel({List<Item>? initialItems}):items=initialItems??[];
   Item getById(int id) =>
      items.firstWhere((element) => element.id == id, orElse: null);
  Item getByPosition(int pos) => items[pos];
}
croxx5f
  • 5,163
  • 2
  • 15
  • 36
0

just convert this static List<Item> items; to static List<Item> items = <Item>[];