Firebase User Doesn't Have Constructor?

Viewed 786

I'm working with Flutter/Dart and Firebase. I'm using provider to grab Firebase user info and I'm seeing this error:

The class 'User' doesn't have a default constructor.
Try using one of the named constructors defined in 'User'.

The code causing the issue is:

providers: [
        ChangeNotifierProvider<AuthProvider>(create: (_) => AuthProvider()),
        StreamProvider<User>.value(
          initialData: User(
            name: 'Friend',
            uid: '0',
          ),
          value: FirebaseAuth.instance.authStateChanges(),
          // initialData: ,
        ),

I don't have a user class. The User class is coming from Firebase so how could I possibly add a constructor to it? Is there a way to get around this constructor error in the initialData field?

There's a UserInfo class that has a constructor. But, when I try using that, I can't set any default values for the fields. I'm getting The named parameter 'uid' isn't defined. Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'uid'

2 Answers

The thing is that you cant create a user object, you need to receive it from Firebase. in the initial data you tried to create an User object so you got an error. honestly i tried to replicate your error but couldnt find from where did you find the named constructors.

some helpful lines of code:

you can get the current logged in user like this:

 User user = FirebaseAuth.instance.currentUser;

or like this if you sign in with email and password:

 final UserCredential signInResponse = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password);

final User user =signInResponse.user;

if you want to create a new user one of the options is:

 final UserCredential createUserResponse = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password);

final User user =createUserResponse.user;

hope this helps, if not tell me what did i miss and ill try to correct my answer :)

So, if I change the initialData value to the following, the errors disappear. Not sure why this works to be honest seems to me like it should cause some errors, but it's not so I'll roll with it for now.

StreamProvider<User>.value(
          initialData: FirebaseAuth.instance.currentUser,
          value: FirebaseAuth.instance.authStateChanges(),
          // initialData: ,
        ),
Related