首页 > 解决方案 > Flutter:Firebase身份验证无需登录即可创建用户

问题描述

我的颤振应用程序中有一个使用 Firebase 身份验证的用户管理功能。firebase_auth我可以使用'screateUserWithEmailAndPassword()功能注册新的用户帐户。

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

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

我遇到了这个答案:Firebase 踢出当前用户,但它是在 javascript 中并且有一个稍微不同的 api。

我怎样才能在飞镖中做同样的事情?

标签: firebasedartflutterfirebase-authentication

解决方案


更新firebase_core ^0.5.0firebase_auth ^0.18.0+1弃用了一些旧课程。

下面是为firebase_core ^0.5.1和更新的代码firebase_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()不会影响默认实例。


推荐阅读