我有一个两步登录表单,用户首先输入他们的电子邮件,然后被带到他们输入密码的下一个页面。在将用户带到密码页面之前,我想检查用户输入的电子邮件是否有效以及它是否存在于 firebase 中。我已经阅读了一些关于使用 fetchSignInMethodsForEmail
的帖子。但是,我不太确定如何实现这一点。
这个想法是,如果电子邮件确实存在,用户将被带到密码页面,但是,如果电子邮件不存在,则会弹出一个带有按钮的快捷栏,将用户带到注册页面。我该怎么做?
这是我目前所拥有的...
FirebaseAuth auth = FirebaseAuth.instance;
final nextButton = Container(
margin: const EdgeInsets.only(
top: 30.0,
),
child: FloatingActionButton(
onPressed: () async {
try {
List<String> userSignInMethods = await auth.fetchSignInMethodsForEmail(email)(
email: _emailController.text,
);
if (userSignInMethods != null) {
final page = LoginPassword();
Navigator.of(context).push(CustomPageRoute(page));
}
} catch (e) {
print(e);
//TODO: Snackbar
}
},
tooltip: 'Next',
backgroundColor: AppTheme.define().primaryColor,
child: Icon(
AppIcons.next_button,
size: 20.0,
),
),
);
fetchSignInMethodsForEmail
未正确实现,我收到错误消息。
答案 0 :(得分:1)
这可能不是你要找的,但我通常做的是将用户存储在 firestore 的集合中,因为这允许我为用户存储多个值,如昵称、图片、点等。如果你想要一些有关如何执行此操作的示例代码,请告诉我
编辑
这是一些帮助您入门的代码。
首先设置firestore并设置一个名为users的集合。使用您的邮件 ID 在其中创建一个文档,并在其中添加您想要的用户字段。如果不这样做,您将收到无法找到集合或未设置 firestore 的错误
在注册时,鉴于电子邮件是可变的电子邮件和密码,请执行以下操作
FirebaseFirestore.instance.collection('users').doc(email).set((){
"email":email,
"pass":pass,
"nick":nick,//You can add more fields or remove them
});
如果您想检查电子邮件是否存在,请执行以下操作
QuerySnapshot query = await FirebaseFirestore.instance.collection('users').where('email',isEqualTo:email).get();
if (query.docs.length==0){
//Go to the sign up screen
}
else {
//Go to the login screen
}
现在要在登录时检查密码,请执行以下操作
QuerySnapshot query = await FirebaseFirestore.instance.collection('users').where('email',isEqualTo:email).get();//You can also pass this query as a parameter when you push the login screen to save some time
if (query.docs[0].get('pass')==pass){
//Go ahead login
}
else{
//Display an error message that password is wrong
}
如果您想存储数据以在用户下次打开应用时自动登录,请查看 Shared Preference 库。
如果要传递用户数据,请创建一个名为 User() 的类
class User {
String email;
String pass;
String nick;
User(this.email,this.nick,this.pass);
}
然后你就可以传递它,轻松管理用户数据
答案 1 :(得分:0)
您可以像我的代码一样尝试 catch
和 exception
。并告诉我。
try {
_firbaseAuth.createUserWithEmailAndPassword(
email: 'ab@gmail.com',
password: '123456'
);
} catch(signUpError) {
if(signUpError is PlatformException) {
if(signUpError.code == 'ERROR_EMAIL_ALREADY_IN_USE') {
/// ab@gmail.com has alread been registered.
}
}
}
答案 2 :(得分:0)
对于查看文档的方法 fetchSignInMethodsForEmail
,An empty List is returned if the user could not be found.
它不能为空,因为该方法返回一个空列表,因此您可以检查长度。 userSignInMethods.length > 0