-1

我使用 Firebase Auth 来允许用户注册。如果用户注册了正确的电子邮件地址和足够安全的密码,他们将注册 Firebase Auth。

我可以注册,但是当我注册失败时,我没有收到错误消息。

String _state = ""; //global

Future signUp(String email, String password) async {
 try {
   UserCredential userCredential = await FirebaseAuth.instance
       .createUserWithEmailAndPassword(email: email, password: password);
 } on FirebaseAuthException catch (e) {
   if (e.code == 'weak-password') {
     setState(() {
       _state = ('The password provided is too weak.');
     });
   } else if (e.code == 'email-already-in-use') {
     setState(() {
       _state = ('The account already exists for that email.');
     });
   }
 } catch (e) {
   setState(() {
     _state = e.toString();
   });
 }
}

参考这里。此代码createUserWithEmailAndPassword()通过将电子邮件地址和密码作为参数传递来执行。我正在尝试使用 try & catch 语句在屏幕上显示登录失败的原因。

但由于某种原因setState()并没有改变Text()具有 global的_state

    @immutable
class signUp extends StatefulWidget {
  static String route = '/signup';
  const  signUp({Key? key}) : super(key: key);

  @override
  _signUp createState() => _signUp();
}

class _signUp extends State<signUp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: myAppBar(context), //custom appBar. ignore this.
        body: const Center(
          child: Text( 
             _state
          ),
        ));
  }
}

我声明Text()StatefulWidget它可以用setState().

但是由于某种原因setState()被忽略并且Text(_state)不被执行。感觉这个问题的原因是在try&catch语句中,但是不知道怎么办。

我应该怎么做才能将注册结果显示为文本?

谢谢你。

4

2 回答 2

0

我可以注册,但是当我注册失败时,我没有收到错误消息。

你能检查一下你的登录是否真的失败了吗?检查您的代码,signUp是一个Future<void>. 您如何处理返回的 UserCredential FirebaseAuth.instance.createUserWithEmailAndPassword

此块捕获异常,而不是成功登录。

catch (e) {
  setState(() {
    _state = "Succeeded!";
  });
}

您还可以在登录请求后检查 UserCredential 以进行调试。

UserCredential userCredential = await FirebaseAuth.instance
       .createUserWithEmailAndPassword(email: email, password: password);
debugPrint(uid: ${userCredential?.user?.uid}
于 2021-09-20T03:00:58.387 回答
0

我改变了这样的代码;这解决了我的问题。

String stateCode = "";
    try {
      UserCredential userCredential = await FirebaseAuth.instance
          .createUserWithEmailAndPassword(email: email, password: password);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        stateCode = ('The password provided is too weak.');
      } else if (e.code == 'email-already-in-use') {
        stateCode = ('The account already exists for that email.');
      } else {
        stateCode = "error: " + e.code;
      }
    } catch (e) {
      stateCode = "error: " + e.toString();
    }

    setState(() {
      _state = (stateCode);
    });

我所要做的就是在发生异常时显示 e.code。

于 2021-09-20T04:00:05.417 回答