A value of type Object?
can’t be returned from the method getUser
because it has a return type of Future<UserModel>
.
Future<UserModel> getUser(String userId) async {
QuerySnapshot userDoc = await _usersCollectionRef.where('userId', isEqualTo: userId).get();
print('user doc: ${userDoc.docs[0].data()}'); //user doc: Instance of 'UserModel'
return userDoc.docs[0].data();
}
Why won’t the future complete even though there clearly is a UserModel
inside the return.
2
Answers
QuerySnapshot is a generic class
QuerySnapshot<T extends Object?>
.In your declaration of
userDoc
you omitted the type parameter:That’s why
T
defaults toObject?
anduserDoc.docs[0].data()
is assumed to return an object of typeT
.The analyzer does not know that the runtimetype of
userDoc.docs[0].data()
will beUserModel
.Your
userDoc
object is an object of type QuerySnapshot. When you call.docs[0]
the type of object that is returned is QueryDocumentSnapshot. When you further call data(), the type of object that is returned isT
, which is a generic type object. So it’s not an instance ofUserModel
but a Map that contains key-value pairs.If you want to convert that data into an object of the
UserModel
class, then you have to create afromMap()
function method as explained in the answer from the following post: