AturicLiqr
AturicLiqr

Reputation: 69

FirebaseAuth.instance.currentUser!uid changes when creating a new user (which is not logged in)

I have just noticed that when I am logged in as a User A and and I create a new User B inside the app using:

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

then... uid of User A (fetched with FirebaseAuth.instance.currentUser!uid) changes to the uid of newly created UserB although User B is not logged in. I just created account for User B and never logged in as User B.

In this case, because I am using FirebaseAuth.instance.currentUser!uid in several places of my app, it starts to "think" I am already User B while I am still logged in as User A.

I thought FirebaseAuth.instance.currentUser!uid gives you the uid of the user who is logged in but it looks otherwise.. Can anyone help me how I can get the uid of the user who is really logged in?

Many thanks upfront for any support!

Upvotes: 1

Views: 902

Answers (1)

Dhirajraje
Dhirajraje

Reputation: 44

As mentioned above, Creating new user will change authState because the new user will be logged in. To avoid this you have to create new of FirebaseAuth.instance. Use the following snippet for the same.

// Create New firebase app instance.
FirebaseApp tempApp = await Firebase.initializeApp(name: 'Some_Random_String_for_app_name', options: Firebase.app().options);
UserCredential userCredential = await FirebaseAuth.instanceFor(app: tempApp).createUserWithEmailAndPassword(email: email, password: pass);
Map<String, dynamic> _user = {
                'sUID': userCredential.user!.uid,
                'sName': name,
                'sEmail': email,
              };

Upvotes: 1

Related Questions