在Flutter上使用电子邮件和密码进行Firebase验证的示例?

时间:2018-06-15 19:12:07

标签: firebase firebase-authentication flutter

首次实施Firebase Auth,也是Flutter dev的新手,我希望使用电子邮件和密码,而不是Google登录。我使用Firebase Auth的唯一示例是匿名或Google。是否有资源/教程显示如何使用signInWithEmailAndPassword方法正确设置调用?

非常感谢!

4 个答案:

答案 0 :(得分:16)

在我的应用程序中,我有一个auth类,因为我不想使用非小部件代码丢弃我的小部件类,但是如果你愿意的话,你可以将这些代码放在你的小部件类中。

在auth.dart中我有:

final FirebaseAuth auth = FirebaseAuth.instance;

Future<FirebaseUser> handleSignInEmail(String email, String password) async {

    final FirebaseUser user = await auth.signInWithEmailAndPassword(email: email, password: password);

    assert(user != null);
    assert(await user.getIdToken() != null);

    final FirebaseUser currentUser = await auth.currentUser();
    assert(user.uid == currentUser.uid);

    print('signInEmail succeeded: $user');

    return user;

  }

Future<FirebaseUser> handleSignUp(email, password) async {

    final FirebaseUser user = await auth.createUserWithEmailAndPassword(email: email, password: password);

    assert (user != null);
    assert (await user.getIdToken() != null);

    return user;

  } 

然后在我的登录/注册屏幕中,我创建了一个我的auth类的实例:

var authHandler = new Auth();

最后,在我的登录按钮onPressed回调中,我有:

onPressed: () {
    authHandler.handleSignInEmail(emailController.text, passwordController.text)
    .then((FirebaseUser user) {
         Navigator.push(context, new MaterialPageRoute(builder: (context) => new HomePage()));
   }).catchError((e) => print(e));
} 

答案 1 :(得分:2)

以下是我服务的一个例子。我要求提供电子邮件,姓名和密码字段。

 registerWithEmail(String name, String email, String password) async {

首先,我检查电子邮件是否已在facebook或其他地方注册。

    List<String> providers = await firebaseAuth.fetchProvidersForEmail(email: email); 

这不是理想的解决方案,但是如果用户已经注册,则需要处理,而不是链接电子邮件与当前用户

    if (providers != null && providers.length > 0) {
      print("already has providers: ${providers.toString()}");
      return handleProviders(providers); 
    }

创建新用户

    FirebaseUser newUser = await firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);
    await newUser.sendEmailVerification();

基本上就是这样。我更新了用户的名称,因为我有。

    var userUpdateInfo = new UserUpdateInfo();
    userUpdateInfo.displayName = name;
    await firebaseAuth.updateProfile(userUpdateInfo);
    await newUser.reload();

以后您可以将用户保存在firestore中,其中用户uid是文档ID。所以我可以稍后再说。

答案 2 :(得分:0)

Git存储库,其中包含使用Flutter的电子邮件/密码登录Firebase 的完整说明示例

这可能会对您有所帮助。

Git回购:https://github.com/myvsparth/firebase_email_signin

分篇文章全文:https://www.c-sharpcorner.com/article/how-to-do-simple-login-with-email-id-in-flutter-using-google-firebase/

答案 3 :(得分:0)

此代码用于注册新用户

  fb_auth.UserCredential userCredential = await fb_auth
      .FirebaseAuth.instance
      .createUserWithEmailAndPassword(email: email, password: password);

这是用于登录以前的用户

fb_auth.UserCredential userCredential = await fb_auth
      .FirebaseAuth.instance
      .signInWithEmailAndPassword(email: email, password: password)

那个 fb_auth 是

import 'package:firebase_auth/firebase_auth.dart' as fb_auth;
相关问题