Flutter Firebase Auth 抛出 NoSuchMethodError:getter 'data' was called on null

时间:2021-04-27 07:22:49

标签: flutter firebase-authentication

在使用 firebaseAuth.createUserWithEmailAndPassword 的电子邮件应用注册过程中,当我尝试上传或保存到 .then 部分中的首选项时,它会引发此错误: NoSuchMethodError: The getter 'data' was called on null.

所以我可以通过导航到一个新屏幕并将用户的 TextFormField 输入的处理推迟到那里来解决这个问题,但它很混乱并且让我感到烦恼。

.then 中做任何大事似乎都有问题,但我真的不知道是什么导致了问题,或者实际上最好的方法是解决此类问题以备将来澄清。教育赞赏!

  void registerToFb() {
    firebaseAuth
        .createUserWithEmailAndPassword(
            email: emailController.text, password: passwordController.text)
        .then((result) async {

      Person user = new Person();
      user.email = emailController.text;
      user.firstName = firstNameController.text;
      user.surname = surnameController.text;
      user.postcode = postcodeController.text;

      user.password = passwordController.text;

      user.city = cityController.text ?? "Edinburgh";
      user.firebaseId = result.user.uid;

      Map<String, dynamic> firebaseUpload = user.toMap();
      print("Attempting to reduce upload");
      firebaseUpload.removeWhere((key, value) => value == null);

      user.country = "GB";

      String path = "${user.country}/${user.city}/People";
      print("Attempting record upload");
      DocumentReference autoId =
          await myFirestore.collection(path).add(firebaseUpload);
      user.personId = autoId.id;

      user.saveToPrefs(prefs);

      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (context) => MyHomePage()));

    }).catchError((err) {
      print("Login thrown an error...\n${err.toString()}");
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Error 10"),
              content: Text("${err.toString()}"),
              actions: [
                ElevatedButton(
                  child: Text("Ok"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                )
              ],
            );
          });
    });

1 个答案:

答案 0 :(得分:1)

我的建议是完全删除 .then() 回调,因为您已将其声明为 async。更好的方法是使整个函数异步,这样您就可以直接在其中执行所有异步代码。

  1. 使函数异步
void registerToFb() async { ...
  1. 将 .then() 回调更改为简单的 await 并将结果存储在您的结果变量中。
var result = await firebaseAuth.createUserWithEmailAndPassword(email: emailController.text, password: passwordController.text);
  1. 我强烈建议用 try/catch 块围绕此语句,以避免未处理的错误:
try {
  var result = await firebaseAuth.createUserWithEmailAndPassword(
    email: emailController.text,
    password: passowrdController.text
  );
} on FirebaseAuthException catch (e) {
  if (e.code == 'weak-password') {
    print('password too weak.');
  } else if (e.code == 'email-already-in-use') {
    print('email already exists');
  }
} catch (e) {
  print(e);
}
  1. 您可能会收到此错误,因为您将 .then() 调用标记为异步,因为它随后以异步方式执行并且数据可能尚未“存在”,但我不确定这个。