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

使用createUserWithEmailAndPassword认证后Firestore未显示用户

问题解决:Firebase Auth创建用户后Firestore无对应文档

核心原因

Firebase身份验证(Auth)和Cloud Firestore是两个独立的服务,调用createUserWithEmailAndPassword只会在Auth系统中创建用户账号,不会自动在Firestore生成对应的用户文档,你需要手动添加写入Firestore的逻辑。

修改后的代码

在用户创建成功后,新增写入Firestore的步骤:

onPressed: () async {
  try {
    final newUserCredential = await FirebaseAuth.instance
        .createUserWithEmailAndPassword(
      email: email ?? 'error',
      password: password ?? 'error',
    );

    // 用户创建成功后,写入Firestore
    if (newUserCredential.user != null) {
      final user = newUserCredential.user!;
      // 向"users"集合添加用户文档,用用户UID作为唯一文档ID
      await FirebaseFirestore.instance
          .collection('users')
          .doc(user.uid)
          .set({
        'email': user.email,
        'uid': user.uid,
        // 可按需添加其他字段,比如注册时间
        'createdAt': FieldValue.serverTimestamp(),
      });

      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => home()),
      );
    }
  } catch (e) {
    print(e);
  }
}

注意事项

  • 确保已在Firebase控制台启用Cloud Firestore服务,并创建了users集合(若使用其他集合名,需同步修改代码中的集合名称)
  • 检查Firestore安全规则,避免权限问题导致写入失败,基础规则示例:
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{userId} {
          allow read, write: if request.auth != null && request.auth.uid == userId;
        }
      }
    }
    
    此规则仅允许用户读写自己的文档,保障数据安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:45:30