且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-26 07:17:45

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

Updated: firebase_core ^0.5.0 and firebase_auth ^0.18.0+1 has deprecated some of the old classes.

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

Below is code updated for firebase_core ^0.5.1 and 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,我目前的工作解决方案是:

I experimented with the firebase authentication api and my current working solution is:

// 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() 的自动登录不会影响默认实例.

Essentially it comes down to creating a new instance of FirebaseAuth so the automatic login from createUserWithEmailAndPassword() do not affect the default instance.