You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否向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字段为空截图


问题原因

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:15:05