Flutter: Firebase Authentication Create User Without Automatically Logging In

Updated: firebase_core ^0.5.0 and firebase_auth ^0.18.0+1 has deprecated some of the old classes as shared in adadion's answer.

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);
}

Original Answer

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);
}

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


Based on Swift's answer I post updated code for this work around.

  Future signUpWithEmailPasswordAdminPastor(String email, String password, String role, String nama, String keuskupan, String kevikepan, String paroki) async {
try {

  FirebaseApp tempApp = await Firebase.initializeApp(name: 'temporaryregister', options: Firebase.app().options);

  UserCredential result = await FirebaseAuth.instanceFor(app: tempApp).createUserWithEmailAndPassword(
      email: email, password: password);

  // create a new document user for the user with uid
  await DatabaseService(uid: result.user.uid).updateUserDataSelf(
      true,
      role,
      nama,
      keuskupan,
      kevikepan,
      paroki,
      '',
      DateTime.now(),
      DateTime.now());

  tempApp.delete();
  return 'OK';
} catch (e) {
  print(e.toString());
  return null;
}
}

Above code works for firebase_core: ^0.5.0 and firebase_auth: ^0.18.0+1.