我已经成功地将firebase添加到我的flutter2.0项目中。我还启用了身份验证。我还可以注册一个新用户。但是,在身份验证后转到主页的逻辑不起作用。即使我输入了错误的用户,我也可以登录。我想如果我输入正确的用户,然后我应该导航到主页,但如果用户没有注册它应该不能导航到下一页。ie..the身份验证的基本用法。但它不会发生在这里。即使我输入了错误的用户,我也能够导航到下一个位置。
Future signInWithEmailAndPassword(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email:email,
password:password,
);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}
}
Future newAccount(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') {
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.toString());
}
}
}
//this is how I can this function and try to navigate to next page.
void logMeIn() {
if (formKey.currentState!.validate()) {
authMethods
.signInWithEmailAndPassword(usernameTextEditingContoller.text,
passwordTextEditingContoller.text)
.then((value) {
print('value is: ');
print(value);
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) {
return Home();
}));
});
}
}**strong text**发布于 2021-04-19 19:35:43
signInWithEmailAndPassword返回一个UserCredential对象。
在您的逻辑中,您正在使用.then((value) {...etc})
此value是signInWithEmailAndPassword的结果。
尝试将您的逻辑更改为:
authMethods
.signInWithEmailAndPassword(usernameTextEditingContoller.text,
passwordTextEditingContoller.text)
.then((value) {
print('value is: ');
print(value);
if(value.user ==null) return "Error in authentication"; // this will prevent your function form going further down the navigation if the usercredential doesn't have a valid user.
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) {
return Home();https://stackoverflow.com/questions/67161130
复制相似问题