Flutter中检查Firebase字段是否存在:存在取值,不存在设空值
Flutter中Firebase字段存在性检查与处理实现
需求说明
- 检查Firestore用户文档中
first_name字段是否存在:存在则返回字段值;不存在则自动添加该字段并设为空字符串 - 额外要求:编写函数验证是否存在
first_name: John的字段值,若first_name字段完全不存在,返回first_name: 空值
优化后的实现代码
// 改用可空类型避免空安全问题 String? userName; Future<void> getUserData() async { final userDoc = FirebaseFirestore.instance .collection("users") .doc(user?.uid); final docSnapshot = await userDoc.get(); if (docSnapshot.exists) { final data = docSnapshot.data(); // 检查first_name字段是否存在 if (data?.containsKey("first_name") ?? false) { userName = data?["first_name"]; // 验证字段值是否为John if (userName == "John") { print("存在first_name: John"); } else { print("first_name字段存在,值为: $userName"); } } else { // 字段不存在,添加空值字段(merge模式避免覆盖其他数据) await userDoc.set({"first_name": ""}, SetOptions(merge: true)); userName = ""; print("first_name字段不存在,已添加并设为空值"); } } else { // 文档不存在时,创建文档并添加空值字段 await userDoc.set({"first_name": ""}); userName = ""; print("用户文档不存在,已创建并添加first_name空值字段"); } } // 单独的检查函数:验证是否存在first_name: John,字段不存在则返回空值 Future<String?> checkFirstNameIsJohn() async { final docSnapshot = await FirebaseFirestore.instance .collection("users") .doc(user?.uid) .get(); if (docSnapshot.exists) { final data = docSnapshot.data(); if (data?.containsKey("first_name") ?? false) { final firstName = data?["first_name"]; return firstName == "John" ? firstName : null; } else { // 字段不存在,返回空值 return ""; } } else { // 文档不存在,返回空值 return ""; } }
代码说明
- 空安全适配:将
userName改为可空类型String?,避免原代码中late String可能触发的空指针异常 - 字段存在性判断:通过
data?.containsKey("first_name")结合空合并运算符,稳妥处理文档数据为null的情况 - 增量更新字段:使用
SetOptions(merge: true)确保仅添加缺失字段,不会覆盖文档中已有的其他数据 - 专属验证逻辑:
checkFirstNameIsJohn()函数单独实现需求中的验证逻辑,返回对应结果
内容的提问来源于stack exchange,提问作者Igor Boldyrev
相关产品推荐
相关产品推荐

