我使用 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语句中,但是不知道怎么办。
我应该怎么做才能将注册结果显示为文本?
谢谢你。