Flutter集成Firebase登录后文档存在判断布尔值更新异常求助
问题分析与解决建议
核心问题排查方向
UID取值错误
你代码中的id变量没有明确来源,登录成功后必须获取当前登录用户的UID才能正确查询对应文档。如果id是空值或错误值,必然会返回false。异步调用的执行顺序问题
如果调用mainAccess()时没有使用await,会导致页面跳转先于Firestore查询完成,出现“跳转后布尔值才变为true”的现象。Firestore权限规则限制
如果Firestore的安全规则未授权登录用户读取DocumentName集合,查询会静默失败(或抛出异常),导致document.exists返回false。
具体修正步骤
1. 修正登录逻辑中的UID获取
登录成功后,通过UserCredential直接获取用户UID,避免依赖currentUser可能的延迟:
mainAccess() async { if (passwordcontroller.text.isEmpty || mailcontroller.text.isEmpty) { // 提示用户完善输入 return; } try { // 登录并获取用户凭证 UserCredential userCredential = await FirebaseAuth.instance .signInWithEmailAndPassword( email: mailcontroller.text, password: passwordcontroller.text); // 确保获取到有效的UID String? uid = userCredential.user?.uid; if (uid == null) { // 处理用户未正常登录的情况 return; } // 执行文档存在性判断 bool docExists = await DatabaseMethods().documentTiendaNExist(uid); if (docExists) { // 跳转主页 Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => MainPage())); } else { // 跳转注册页 Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => RegistrationPage())); } } on FirebaseAuthException catch (e) { // 处理登录错误(如邮箱密码错误) print(e.message); } }
2. 优化文档查询方法
简化方法逻辑,同时增加空ID判断避免无效查询:
Future<bool> documentTiendaNExist(String id) async { if (id.isEmpty) return false; DocumentSnapshot<Map<String, dynamic>> document = await FirebaseFirestore .instance .collection("DocumentName") .doc(id) .get(); return document.exists; }
3. 确保异步方法的正确调用
调用mainAccess()时必须使用await,比如在按钮点击事件中:
ElevatedButton( onPressed: () async { await mainAccess(); }, child: const Text("登录"), )
4. 检查Firestore安全规则
确保登录用户有权限读取DocumentName集合,修改firestore.rules为:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /DocumentName/{docId} { allow read, write: if request.auth != null; } } }
内容的提问来源于stack exchange,提问作者Anthony Von Der Kreuz
相关产品推荐
相关产品推荐

