gpt4 book ai didi

flutter - 将项目添加到 Dart/Flutter 中嵌套 map 内的列表中

转载 作者:行者123 更新时间:2023-12-03 03:35:54 26 4
gpt4 key购买 nike

当我打电话时addItemToCart({"key": "val"}) ,我无法将项目添加到 Dart/Flutter 中嵌套 map 内的列表中。 var list = cart['items']给了我一个空值,但我初始化了类(class)成员 cart已经。

它到底有什么问题?

import 'package:flutter/material.dart';
import 'dart:collection';

class PData extends ChangeNotifier {
dynamic cart = {"items": []};

int itemCount = 0;
String uid;
String phoneNumber;

void addItemToCart(val){
var list = cart['items'];
print("list ");
print (list);

list.add(val);
notifyListeners();
}

}

给出以下错误:
I/flutter ( 5763): list 
I/flutter ( 5763): null

════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
The method 'add' was called on null.
Receiver: null

尝试调用:add(_LinkedHashMap len:6)

最佳答案

您需要添加 .toList() 才能启动。请参阅下面的示例代码片段:

var list = cart['items'];
var realList = list.toList();
print("list ");
print (list);

realList.add("soap");
print(realList); // This prints [soap]
realList.add("Pen");
print(realList); // This prints [soap, pen]

关于flutter - 将项目添加到 Dart/Flutter 中嵌套 map 内的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61198096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com