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

2024年Flutter中如何在注册后保存用户数据到Cloud Firestore

如何在Flutter中创建Firebase用户同时保存数据到Cloud Firestore(2024适配版)

先确保项目已正确集成firebase_auth和firebase_firestore最新版本依赖,再按以下方式修改你的代码:

修改后的完整代码

onPressed: () async {
  // 可在此处添加加载状态(比如显示Spinner)
  try {
    // 1. 创建Firebase Auth账号
    final credential = await _auth.createUserWithEmailAndPassword(
      email: email,
      password: password,
    );

    final user = credential.user;
    if (user == null) {
      print('用户创建失败');
      return;
    }

    // 2. 准备要存入Firestore的用户数据
    Map<String, dynamic> userData = {
      'email': email,
      'personIdentity': widget.personIdentity,
      'createdAt': DateTime.now(), // 可选:记录账号创建时间
      // 可按需添加其他字段,比如姓名、手机号等
    };

    // 3. 将数据写入Cloud Firestore
    await FirebaseFirestore.instance
        .collection('users') // 自定义用户集合名称
        .doc(user.uid) // 用Auth返回的uid作为文档ID,确保账号与数据一一绑定
        .set(userData);

    // 4. 根据身份跳转对应页面
    if (widget.personIdentity == 'Student') {
      Navigator.pushNamed(context, StudentScreen.id);
    } else {
      Navigator.push(context, MaterialPageRoute(
        builder: (context) => const DriverScreen(dPersonIdentity: 'Driver'),
      ));
    }
  } on FirebaseAuthException catch (e) {
    if (e.code == 'weak-password') {
      print('密码强度不足');
    } else if (e.code == 'email-already-in-use') {
      print('该邮箱已注册账号');
    }
  } catch (e) {
    print('操作失败:$e');
  }
},

关键注意事项

  • 账号与数据绑定:用Firebase Auth返回的user.uid作为Firestore文档ID,能保证Auth账号和用户数据一一对应,后续查询用户数据时直接用uid即可,避免数据混乱。
  • Firestore安全规则配置:必须配置安全规则,允许新用户写入自己的文档,示例规则如下:
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{userId} {
          allow create, read: if request.auth != null && request.auth.uid == userId;
        }
      }
    }
    
  • 异常处理:数据写入环节也要包裹在try-catch中,避免出现“账号创建成功但数据保存失败”的情况,可根据需求添加弹窗提示用户操作结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:00:01