Home > database >  Getting a null user id while accessing the id of current user in firebase flutter?
Getting a null user id while accessing the id of current user in firebase flutter?

Time:02-06

Actually I'm trying to get current user id after authentication but I don't know how to do it. While registering email/password authentication only stores email, password as well as uid. I tried to fetch that uid by calling following function after pressing login button but it return null. I am not able to get the uid of current user.

Calling a function after pressing login button:

final FirebaseAuth auth = FirebaseAuth.instance;

Future<void> inputData() async {
  final User? user = await auth.currentUser;
  final uid = user?.uid;
  // here you write the codes to input the data into firestore
  print("User id: ${uid}");
}

You can see in the console it prints null: enter image description here

enter image description here

CodePudding user response:

Most likely your inputData function runs before the user is signed in. To ensure your code can properly react to when the user is signed in or out, use an auth state listener as shown in the first snippet in the documentation on getting the current user.

Future<void> inputData() async {
  FirebaseAuth.instance
    .authStateChanges()
    .listen((User? user) {
      if (user != null) {
        print(user.uid);
      }
    });
}

CodePudding user response:

one reason why you might be getting null is you're not awaiting the getToken function, so make it a future and await it, I'm sure you'll get the token provided the user is authenticated.

  • Related