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

Flutter Firebase:通过mobile字段查找文档并更新growScore(无则不操作)

Flutter Firebase 用户growScore字段更新问题解决

需求说明

在Flutter Firebase应用中,需根据mobile字段查找用户文档:

  • 找到文档:更新growScore字段(post_type为"Bad"时减5,否则加5)
  • 未找到文档:不执行任何操作

用户模型字段

final Map user;
final String mobile;
final String business_name;
final String business_address;
final String aadhar;
final String pan;
final bool isPhoneVerified;
final int growScore;
final String sector;
final String profile_picture;
final String business_picture;
final String uid;
final String about;

当前尝试的无效代码

updateGrowScore(String phoneNumber, String post_type) async {
  await ref
      .watch(firestoreProvider)
      .collection("my_users")
      .where("mobile", isEqualTo: phoneNumber)
      .get()
      .then((value) => value.docs.map((e) {
            ref
                .watch(firestoreProvider)
                .collection('my_users')
                .doc(e.id)
                .update({
              'growScore': FieldValue.increment(post_type == "Bad" ? -5 : 5)
            });
            print("successfully updated");
          }));
}

问题分析与修复方案

原代码存在两个核心问题:

  1. 使用map遍历文档时未等待异步更新完成,await仅作用于get()请求,导致函数提前结束
  2. 重复调用ref.watch(firestoreProvider)冗余,应复用Firestore实例

修复后的代码

Future<void> updateGrowScore(String phoneNumber, String postType) async {
  // 单次获取Firestore实例,避免重复监听
  final firestore = ref.watch(firestoreProvider);
  // 根据手机号查询用户文档
  final querySnapshot = await firestore.collection("my_users").where("mobile", isEqualTo: phoneNumber).get();

  if (querySnapshot.docs.isNotEmpty) {
    // 计算增减值
    final incrementValue = postType == "Bad" ? -5 : 5;
    // 遍历更新找到的文档(若mobile唯一,可直接取docs.first)
    for (final doc in querySnapshot.docs) {
      await firestore.collection("my_users").doc(doc.id).update({
        'growScore': FieldValue.increment(incrementValue)
      });
      print("用户${doc.id}的growScore已更新");
    }
  } else {
    print("未找到手机号为$phoneNumber的用户");
  }
}

额外优化建议

  • 若mobile字段是集合唯一标识,可直接用querySnapshot.docs.first替换遍历,减少不必要循环
  • 为mobile字段创建Firestore索引,提升大数据量下的查询效率
  • 添加错误捕获,处理网络或权限异常:
Future<void> updateGrowScore(String phoneNumber, String postType) async {
  final firestore = ref.watch(firestoreProvider);
  try {
    final querySnapshot = await firestore.collection("my_users").where("mobile", isEqualTo: phoneNumber).get();
    if (querySnapshot.docs.isNotEmpty) {
      final incrementValue = postType == "Bad" ? -5 : 5;
      await firestore.collection("my_users").doc(querySnapshot.docs.first.id).update({
        'growScore': FieldValue.increment(incrementValue)
      });
      print("growScore更新成功");
    }
  } catch (e) {
    print("更新失败:$e");
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:55:14