Flutter中如何获取登录用户自动生成的Firestore文档ID(非UID)
解决Flutter中Firestore获取用户文档ID的问题
你的代码问题出在异步操作的处理上:usersRef.where(...).get()是异步方法,使用then回调时,外层函数会直接执行到return "empty -1",而回调里的return docId根本不会影响函数的返回值,所以你始终拿到的是默认返回值。
正确的做法是将函数改为异步函数,用async/await等待Firestore查询完成:
Future<String> getDocId() async { final usersRef = FirebaseFirestore.instance.collection('users'); final uid = FirebaseAuth.instance.currentUser?.uid; if (uid == null) { return "empty -1"; } try { final querySnapshot = await usersRef.where('uid', isEqualTo: uid).get(); if (querySnapshot.docs.isNotEmpty) { final docId = querySnapshot.docs[0].id; print(docId); return docId; } else { // 未找到对应用户文档的情况 return "no doc found"; } } catch (e) { // 处理查询异常 print("查询出错: $e"); return "error"; } }
关键修改点:
- 将函数声明为
Future<String>,并添加async关键字 - 用
await替代then,等待查询结果返回后再继续执行 - 增加异常捕获,处理Firestore查询可能出现的错误
- 提前判断
uid为空的情况,避免后续无效查询
调用这个函数时,也需要用await或者then来获取结果:
// 示例调用 void fetchDocId() async { String docId = await getDocId(); print("用户文档ID: $docId"); }
内容的提问来源于stack exchange,提问作者Skar
相关产品推荐
相关产品推荐

