firebase - Flutter:Firebase身份验证无需登录即可创建用户

标签 firebase dart flutter firebase-authentication

我的 Flutter 应用中有一个使用 Firebase 身份验证的用户管理功能。我可以使用 firebase_authcreateUserWithEmailAndPassword() 函数注册新用户帐户。

return await FirebaseAuth.instance.
    createUserWithEmailAndPassword(email: email, password: password);

问题是当注册成功时,即使我已经登录,它也会自动将我的 FirebaseAuth 实例验证为新用户。

我遇到了这个答案: Firebase kicks out current user 但它是用 javascript 编写的,并且 api 略有不同。

如何在 dart 中做同样的事情?

最佳答案

更新:firebase_core ^0.5.0firebase_auth ^0.18.0+1 已弃用一些旧类。

以下是 firebase_core ^0.5.1firebase_auth ^0.18.2 的代码更新。

static Future<UserCredential> register(String email, String password) async {
    FirebaseApp app = await Firebase.initializeApp(
        name: 'Secondary', options: Firebase.app().options);
    try {
        UserCredential userCredential = await FirebaseAuth.instanceFor(app: app)
        .createUserWithEmailAndPassword(email: email, password: password);
    }
    on FirebaseAuthException catch (e) {
      // Do something with exception. This try/catch is here to make sure 
      // that even if the user creation fails, app.delete() runs, if is not, 
      // next time Firebase.initializeApp() will fail as the previous one was
      // not deleted.
    }
    
    await app.delete();
    return Future.sync(() => userCredential);
}

原答案

我尝试了 firebase 身份验证 api,我目前的工作解决方案是:

// Deprecated as of `firebase_core ^0.5.0` and `firebase_auth ^0.18.0`.
// Use code above instead.

static Future<FirebaseUser> register(String email, String password) async {
    FirebaseApp app = await FirebaseApp.configure(
        name: 'Secondary', options: await FirebaseApp.instance.options);
    return FirebaseAuth.fromApp(app)
        .createUserWithEmailAndPassword(email: email, password: password);
}

基本上它归结为创建一个新的 FirebaseAuth 实例,因此 createUserWithEmailAndPassword() 的自动登录不会影响默认实例。

关于firebase - Flutter:Firebase身份验证无需登录即可创建用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54412712/

相关文章:

ios - Firebase 通知记录/日志 API

ios - 原生脚本 | Firebase 通知不起作用

ios - 点击更新 tableView 单元格中的 Firebase 数据

dart - 如何使用 Dart http_server :VirtualDirectory

firebase - 管理 Cloud Firestore 中的非规范化/重复数据

json - 将Json转换为包含对象列表的对象时出错

Flutter:如何使用 HapticFeedback

flutter - 如何在 flutter 中输入新信息后创建动态页面(新页面)

flutter - 使用空格而不是逗号作为千位分隔符来格式化数字

android - 在 "flutter doctor"中显示关于 Android 工具链的错误