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

Flutter中Firebase的FieldValue.arrayUnion无法保存重复列表元素

问题:Firestore使用FieldValue.arrayUnion无法保存含重复元素的数组

我用Flutter开发移动应用,基于Firebase Firestore存储数据。想要向数据库中添加包含重复值的数组,但使用FieldValue.arrayUnion(stats)时,仅能保存不同值的元素。例如生成的列表为["0-0-0-0", "0-0-0-0", "0-0-0-0"],Firebase中却只保存了一个"0-0-0-0";当列表元素值不同时则可正常保存。通过Firebase官网手动添加重复元素无问题,但Flutter端使用arrayUnion就出现该问题。

原代码

for(int i = 0; i < 3;i++)
{
    stats.add("0-0-0-0");
}

FirebaseFirestore.instance
    .collection("xxxx")
    .doc(auth.currentUser!.uid)
    .collection("xxxxx")
    .doc(xxxxx)
    .set({
  "Lang_1": FieldValue.arrayUnion(xxxxx),
  "Lang_2": FieldValue.arrayUnion(xxxxx),
  "Length": counter,
  "Stats": FieldValue.arrayUnion(stats),
});

问题原因

FieldValue.arrayUnion的核心设计逻辑是仅向数组中添加不存在的元素,目的是自动去重。所以无论传入多少个重复值,最终只会在数组中保留一个该值。如果需要保存包含重复元素的数组,不能使用arrayUnion方法。

解决方案代码

直接将包含重复元素的列表赋值给字段,而非通过arrayUnion处理:

stats.clear();
for (int i = 0; i < 3; i++) {
  stats.add("0-0-0-0");
}
final docData = {
  "x": x,
  "x": x,
  "x": x,
  "Stats": stats,
};

FirebaseFirestore.instance
    .collection("x")
    .doc(x)
    .collection("x")
    .doc(x)
    .set(docData);

内容的提问来源于stack exchange,提问作者Hamza BOZKURT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:10:10