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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:45:01