setState() 是否被 try & catch 忽略?

Is setState() ignored by try & catch?

我使用 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();
   });
 }
}

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

但由于某些原因 setState() 不会更改具有全局 _state.

Text()
    @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
          ),
        ));
  }
}

我在 StatefulWidget 中声明了 Text() 以便它可以用 setState() 更新。

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

如何将注册结果显示为文本?

谢谢。

I can register, but when I fail to sign up, I don't get an error.

请问您是不是真的登录失败了?检查您的代码,signUpFuture<void>。您如何处理 FirebaseAuth.instance.createUserWithEmailAndPassword 返回的 UserCredential?

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

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

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

UserCredential userCredential = await FirebaseAuth.instance
       .createUserWithEmailAndPassword(email: email, password: password);
debugPrint(uid: ${userCredential?.user?.uid}

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

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。