skip to Main Content

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


  1. QuerySnapshot is a generic class QuerySnapshot<T extends Object?>.

    In your declaration of userDoc you omitted the type parameter:

    QuerySnapshot userDoc = await _usersCollectionRef.where(
      'userId', isEqualTo: userId,
    ).get();
    

    That’s why T defaults to Object? and userDoc.docs[0].data() is assumed to return an object of type T.
    The analyzer does not know that the runtimetype of userDoc.docs[0].data() will be UserModel.

    Login or Signup to reply.
  2. 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 is T, which is a generic type object. So it’s not an instance of UserModel 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 a fromMap() function method as explained in the answer from the following post:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search