Home > database >  trying to get user uid after creating account but getting null
trying to get user uid after creating account but getting null

Time:12-13

I am trying to get the user uid after creating an account, so I can create a document on firestore with the uid as document id. The problem is that I get only null. Here's the function I am using:

void setUserDoc(name, lastName, email) {
  FirebaseAuth auth = FirebaseAuth.instance;
  String? uid = auth.currentUser?.uid;
  DocumentReference<Map<String, dynamic>> usersRef =
      FirebaseFirestore.instance.collection('users').doc(uid);
  usersRef.set({
    'name': name,
    'lastName': lastName,
    'email': email,
    'createdAt': FieldValue.serverTimestamp(),
  });
  return;
}

and here is part of the widget:

Padding(
 padding: const EdgeInsets.only(top: 50, right: 50, left: 50),
 child: ElevatedButton(
   onPressed: () {
     setState(() {
        _passwordError = validatePassword(passwordController.text);
        _emailError = validateEmail(emailController.text);
     });
     if (_passwordError == null && _emailError == null) {
     authService.createUserWithEmailAndPassword(
       emailController.text,
       passwordController.text,
    );
    setUserDoc(
      nameController.text,
      lastNameController.text,
      emailController.text,
    );
    Navigator.of(context).pushNamed('/');
  }
},

what am I missing?

CodePudding user response:

It looks like you're accessing auth.currentUser before it's initialized, and then not handling the null it gives back well.

Since it takes time to restore the authentication state when the app starts, you should listen to the auth state. With that, your code would be:

FirebaseAuth.instance
  .authStateChanges()
  .listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
      String? uid = user.uid;
      DocumentReference<Map<String, dynamic>> usersRef =
          FirebaseFirestore.instance.collection('users').doc(uid);
      usersRef.set({
        'name': name,
        'lastName': lastName,
        'email': email,
        'createdAt': FieldValue.serverTimestamp(),
      });
    }
  });

CodePudding user response:

I think instead of creating an instance of FirebaseAuth auth, and trying to get the uid from it.

Instead you need to create an instance of User (earlier FirebaseUser) and then get the uid from it.

try this.

late User user;
String? uid;
void setUserDoc(name, lastName, email) {
  user= FirebaseAuth.instance.currentUser!;
  uid = user.uid;
  DocumentReference<Map<String, dynamic>> usersRef =
      FirebaseFirestore.instance.collection('users').doc(uid);
  usersRef.set({
    'name': name,
    'lastName': lastName,
    'email': email,
    'createdAt': FieldValue.serverTimestamp(),
  });
  return;
}
  • Related