Issue
I’m getting the below error:
The return type 'AuthUser?' isn't a 'User?', as required by the closure's context.
From the below code:
class AuthService {
final FirebaseAuth authInstance = FirebaseAuth.instance;
final FirebaseFirestore firestoreInstance = FirebaseFirestore.instance;
Stream<User?> get currentUser => authInstance.authStateChanges().map(
(User? firebaseUser) => (firebaseUser != null) ? AuthUser.fromFirebaseUser(user: firebaseUser) : null,
);
}
Below is the code for the model class:
import 'package:firebase_auth/firebase_auth.dart';
class AuthUser {
String? uid;
String? email;
String? userName;
AuthUser({
required this.uid,
required this.email,
required this.userName,
});
AuthUser.fromFirebaseUser({User? user}) {
uid = user!.uid;
email = user.email;
userName = user.displayName;
}
}
I would also like to know how to consume this stream using the StreamProvider<AuthUser>.value
.
Please do let me know whether Consumer
widget or the Provider.of(context)
widget, which one would be appropriate to access the values.
Thanks in advance for your help.
Solution
Your stream is mapping the User
model from Firebase to your AuthUser
model.
So you need to change the return type of the currentUser
getter.
Change this:
Stream<User?> get currentUser => authInstance.authStateChanges().map(
(User? firebaseUser) => (firebaseUser != null) ? AuthUser.fromFirebaseUser(user: firebaseUser) : null,
);
to this:
Stream<AuthUser?> get currentUser => authInstance.authStateChanges().map(
(User? firebaseUser) => (firebaseUser != null) ? AuthUser.fromFirebaseUser(user: firebaseUser) : null,
);
Answered By – Victor Eronmosele
Answer Checked By – Willingham (FlutterFixes Volunteer)