能否向Firestore单个字段传入列表?列表传入后为空求解决建议
能否向Firestore的单个字段传入列表?
我尝试将列表传入Firestore,但对应的字段显示为空,请问需要修改哪里或有什么建议?
从Firebase获取列表的代码
List<ItemSell>? _itemsell; Future getItemList() async { var itemData = await FirebaseFirestore.instance .collection('users') .doc(uid) .collection('cart') .get(); setState(() { _itemsell = List.from(itemData.docs.map((doc) => ItemSell.fromSnapshot(doc))); }); }
添加到Firebase的代码
FirebaseFirestore.instance .collection("users") .doc(uid) .collection("orders") .add({ "uid": uid, "mid": widget._merchant.userid, "uname": username, "utel": usertel, "mname": widget._merchant.name, "mtel": widget._merchant.tel, "sellitemlist": _itemsell, })
ItemSell类代码
class ItemSell { String type = ''; String brand = ''; String model = ''; String itemid = ''; String itemcartid = ''; double itemprice = 0.0; ItemSell(this.type, this.brand, this.model, this.itemid, this.itemprice); Map<String, dynamic> toJson() => { 'itemtype': type, 'itembrand': brand, 'itemmodel': model, 'uid': itemid, 'itemprice': itemprice, 'icid': itemcartid, }; ItemSell.fromSnapshot(snapshot) : type = snapshot.data()['itemtype'], brand = snapshot.data()['itembrand'], model = snapshot.data()['itemmodel'], itemprice = snapshot.data()['itemprice'], itemcartid = snapshot.data()['icid'], itemid = snapshot.data()['uid']; }
问题截图

问题原因
Firestore无法直接序列化自定义的ItemSell对象,直接传入_itemsell列表时,Firestore不知道如何将对象转化为可存储格式,导致字段为空。
修改方案
添加数据时,将_itemsell中的每个ItemSell对象通过toJson()方法转为Map类型,再存入Firestore:
修改添加代码里的sellitemlist字段:
"sellitemlist": _itemsell?.map((item) => item.toJson()).toList(),
完整修改后的添加代码:
FirebaseFirestore.instance .collection("users") .doc(uid) .collection("orders") .add({ "uid": uid, "mid": widget._merchant.userid, "uname": username, "utel": usertel, "mname": widget._merchant.name, "mtel": widget._merchant.tel, "sellitemlist": _itemsell?.map((item) => item.toJson()).toList(), })
额外注意事项
- 确保
_itemsell不为空,可添加非空判断避免传入null导致字段异常。 - 后续从Firestore读取
sellitemlist时,需将每个Map重新转为ItemSell对象,逻辑可参考获取购物车列表的实现。
内容的提问来源于stack exchange,提问作者Noikun Desuka
相关产品推荐
相关产品推荐

