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

如何修改Cloud Firestore文档中的键值对?代码未生效如何排查?

问题排查与修复方案

1. 核心问题:异步操作未等待&无错误捕获

你当前的select方法是同步方法,调用异步的editStufe时没有添加await,导致方法执行时不会等待Firestore更新操作完成,直接执行后续的print(key),同时如果操作抛出异常你也无法感知。
首先修改select方法为异步,添加错误捕获:

Future<void> select(String key) async {
  int? targetValue;
  switch(key) {
    case 'Stufe 1': targetValue = 1; break;
    case 'Stufe 2': targetValue = 2; break;
    case 'Stufe 3': targetValue = 3; break;
    case 'Stufe 4': targetValue = 4; break;
    case 'Stufe 5': targetValue = 5; break;
    case 'Stufe 6': targetValue = 6; break;
  }
  if (targetValue != null) {
    try {
      await stufenService.editStufe('Stufe', targetValue);
      print('更新成功,key: $key');
    } catch (e) {
      print('更新失败,错误信息: $e');
    }
  }
  print(key);
}

2. editStufe方法兼容文档不存在的场景

Firestore的update方法仅能更新已存在的文档,如果对应用户ID的文档还没创建,update会直接报错。修改editStufe方法兼容不存在的场景:

final CollectionReference userTodos = FirebaseFirestore.instance.collection('userTodos');
  
Future editStufe(String Stufe, int i) async{
  return await userTodos.doc(userID).set({Stufe: i}, SetOptions(merge: true));
}

3. 额外校验项

  • 确认userID变量是非空的有效值,不要传递null或者不存在的文档ID
  • 检查Firestore的安全规则,确保你当前登录的用户有该文档的写入权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:30:05