我试着将每个用户的数据保存在云Firestore中,在Stackoverflow上搜索,感觉好坏参半,因为旧的解决方案在2024年给出了错误,同时我是新手,我下面的代码在按下注册按钮时创建了一个新用户,我如何也保存每个用户的数据呢?

 onPressed: () async {
    //show spinner
    //create new account
    try {
      final credential = await _auth
          .createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      print(widget.personIdentity);
      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('The password provided is too weak.');
      } else if (e.code == 'email-already-in-use') {
        print('The account already exists for that email.');
      }
    } catch (e) {
      print(e);
    }
  },

推荐答案

创建一个Map<String,dynamic>并添加详细信息,然后使用firestore存储数据:

Future<void> signUp(String email, String password, String name) async {
  try {
    UserCredential credential = await _auth.createUserWithEmailAndPassword(
      email: email,
      password: password,
    );

    // this method will be used store data
    Map<String, dynamic> user = {
      'uid': credential.user!.uid.toString(),
      'name': name,
      'email': email
    };

    // this will store user data in USERS collection with docId of UID of the user
    // eg: users/uid/here
    await _firestore
        .collection('users')
        .doc(credential.user!.uid)
        .set(user); //set method requires a Map<String,dynamic>
  } on FirebaseAuthException catch (_) {}
}

Flutter相关问答推荐

为什么我需要等待重新访问Firestore数据库,即使它已经做了之前?

try 在Flutter应用程序中传递变量到FirebaseFirestore Where子句

如何组合匹配器

遇到图像路径格式问题

在选项卡栏视图中搜索和筛选不起作用

在VSCode中运行应用程序而不进行调试时,控制台仍显示为调试模式

Firebase WHERE过滤器在日期字段中不起作用

Flutter 附近的连接

Flutter:在 pubspec.yaml 中找不到assets资源

Flutter 火焰相机抖动已弃用

Android 模拟器在 Apple M2 芯片 EXC_BAD_ACCESS / KERN_INVALID_ADDRESS 上随机崩溃

Flutter 应用程序在启动画面冻结(java.lang.RuntimeException:无法启动活动 ComponentInfo)

Flutter - 展开图标无法正常工作

是否有可能减少代码的编写,例如:ref.read(countProvider.notifier) - 在构建方法中?

使用 Riverpod 和 copyWith 方法更新数据类中列表中变量的值

Flutterfire Configure - 未处理的异常和没有 firebase 初始化

如何在 cupertino switch flutter 中添加文本

Flutter Serverpod 在示例项目上返回 400 错误

如何使用列Flutter 中文本占用的空间来控制svg宽度

在 Flutter 中更新对象实例属性的最佳实践是什么?该实例嵌套在提供程序类的映射中,如下所示