【问题标题】:"Non-nullable instance field '_items' must be initialized.\nTry adding an initializer it"必须初始化不可为空的实例字段 '_items'。\n尝试添加一个初始化器
【发布时间】:2021-06-29 12:58:00
【问题描述】:

我正在尝试为购物车制作一个模式,但这给了我一个错误。 我的 dart sdk 版本:2.12.0>3.0.0

我尝试在此地图之前使用“延迟”,但它在输出结果中出现错误,即延迟初始化错误:字段“_items”尚未初始化

 Map<String, CartItem> _items;




import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';

class CartItem with ChangeNotifier {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem(
      {required this.id,
      required this.title,
      required this.price,
      required this.quantity});
}

class Cart with ChangeNotifier {
  Map<String, CartItem> _items;       //error _items

  Map<String, CartItem> get items {
    return {..._items};
  }

  int get itemcount {
    return _items.length;
  }

  void addItems(String productId, double price, String title) {
    if (_items.containsKey(productId)) {
      _items.update(
        productId,
        (existing) => CartItem(
            id: existing.id,
            title: existing.title,
            price: existing.price,
            quantity: existing.quantity + 1),
      );
    } else {
      _items.putIfAbsent(
          productId,
          () => CartItem(
              id: DateTime.now().toString(),
              title: title,
              price: price,
              quantity: 1));
    }
  }
}

【问题讨论】:

    标签: flutter


    【解决方案1】:

    {}空映射初始化_items变量。

    Map<String, CartItem> _items = {}; 
    

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 2021-09-24
      • 2021-10-11
      • 2021-08-27
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多