如何使用地图提供程序包<String, ModelClass>

How to use Provider Package for Map<String, ModelClass>

当我将 'Late' 与 Map _items 一起使用时; 延迟初始化错误已删除。 但如果列表为空,则会出现延迟初始化错误。

 import 'package:flutter/material.dart';
    import 'package:shop1/model/cart_item.dart';

    class ShopProvider with ChangeNotifier {
    late Map<String, CartItem> _items;

    ShopProvider() {

    _items = {
      '1': CartItem(
          id: '1',
          title: 'sikki',
          imgUrl: 'assets/cocacola.png',
          qnt: 2,
          price: 13)
    };

  }

  Map<String, CartItem> get items => _items;
  set items(Map<String, CartItem> value) {
    _items = value;
  }
}

您可以在其声明中初始化它,而不是后期初始化:

class ShopProvider extends ChangeNotifier {
  Map<String, CartItem> _items = [];

  // omitted
}

您也可以通过传递的参数或通过初始化列表在构造函数中对其进行初始化:

class ShopProvider extends ChangeNotifier {
  Map<String, CartItem> _items;

  // Passing an argument
  ShopProvider(this._items);

  // OR passing a named argument
  ShopProvider({ 
    required Map<String, CartItem> items,
  }): _items = items;

  // OR using initializer list only
  ShopProvider(): _items = [];

  // rest of class omitted
}

对于更多上下文,class 的所有成员都应该在构造函数主体运行时已经初始化。所以:

ShopProvider() {
  // All members must be initialized BEFORe code in this block runs,
  // or otherwise be marked as "late" - but you must be sure
  // to initialize any "late" variables before they are used.
}

这就是我们使用初始化列表的原因 - 这些初始化发生在之前构造函数主体,成员字段声明中的初始化也是如此。

最后,语法:

ShopProvider(this._items);

实际上只是一个 shorthand 这样做:

ShopProvider(Map<String, CartItem> items): _items = items;