firebaseflutterdartfirebase-authentication

Flutter The getter 'uid' isn't defined for the type 'UserCredential'


I have been working on firebase real time database with flutter and I want to create a new user with email and password but when I want to get the uid it says like the title. I don't know what's wrong.

 Future validateForm() async {
    FormState formState = _formKey.currentState;

    if (formState.validate()) {
      formState.reset();
      User user =  firebaseAuth.currentUser;
      if (user == null) {
        firebaseAuth
            .createUserWithEmailAndPassword(
                email: _emailTextController.text,
                password: _passwordTextController.text)
            .then((user) => {
              _userServices.createUser(
            {
            "username": _nameTextController.text,
            "email": _emailTextController.text,
            "userId": user.uid,
            "gender": gender,
            }
        )
        }).catchError((err) => {print(err.toString())});

    Navigator.pushReplacement(
    context, MaterialPageRoute(builder: (context) => HomePage()));

      }
    }
  }

and here is my user.dart:

import 'package:firebase_database/firebase_database.dart';
class UserServices{
  FirebaseDatabase _database = FirebaseDatabase.instance;
  String ref = "users";

  createUser(Map value){
    _database.reference().child(ref).push().set(
      value
    ).catchError((e) => { print(e.toString())});
  }
}

Solution

  • createUserWithEmailAndPassword() returns a Future<UserCredential>. Inside the class UserCredential you have a property called user which retrieves the currently created user and returns a type of User. Therefore you need to do the following:

            firebaseAuth
                .createUserWithEmailAndPassword(
                    email: _emailTextController.text,
                    password: _passwordTextController.text)
                .then((user) => {
                  _userServices.createUser(
                {
                "username": _nameTextController.text,
                "email": _emailTextController.text,
                "userId": user.user.uid,
                "gender": gender,
                }
    

    user argument in the callback is of type UserCredential, the .user is of type User and the uid is a property inside the class User.