Flutter Firebase 'List<Future<CustomClass>>' 类型的值无法分配给 'List< CustomClass >?' 类型的变量

Flutter Firebase A value of type 'List<Future<CustomClass>>' can't be assigned to a variable of type 'List< CustomClass >?'

我的 FutureBuilder 出现问题。它应该将自定义 class 'GeoPost' 映射到来自 firebase 查询的 'List' 但在我的代码中某处它没有将 Geopost 列表读取为非 Future

这里是出现错误的代码:

FutureBuilder(
            future: postsRef.get().then((doc) {
              geoPosts = doc.docs.map((doc) async => await GeoPost.fromDoc(doc)).toList();
            }),
            builder: (context, snapshot) { }

自定义 class 和功能:

    class GeoPost {
      final String caption;
      final String postId;
      final String authorId;
      final int likesCount;
      final int commentCount;
      final Position position;
      final Timestamp timeStamp;
      final String? imageUrl;
      final Userdata authordata;
    
      GeoPost(this.caption, this.postId, this.authorId, this.likesCount, this.commentCount, this.position, this.timeStamp, this.imageUrl, this.authordata);
    
      static Future<GeoPost> fromDoc(DocumentSnapshot doc) async {
        return GeoPost.fromDocument(doc, await getPostUserDataFromFirestore(doc['userId']));
    
      }
    
      factory GeoPost.fromDocument(DocumentSnapshot doc, Userdata author) {
        return GeoPost(
            doc['caption'],
            doc['postId'],
            doc['userId'],
            doc['likeCount'] ?? 0,
            doc['commentCount'] ?? 0,
            doc['position'],
            doc['timeStamp'],
            doc['imageUrl'],
            author
        );
      }

Future<void> getPostUserDataFromFirestore (String did) async {
    return Userdata.fromDoc(await usersRef.doc(uid).get());
  }
    }

错误:

Error: A value of type 'List<Future<GeoPost>>' can't be assigned to a variable of type 'List<GeoPost>?'.
  • 您需要等待 List<Future<GeoPost> 中的所有 Future(将它们转换为 List<GeoPost>),然后再将它们分配给 List<GeoPost> 类型的变量.

    将您的 FutureBuilder 代码更新为:

    FutureBuilder<List<GeoPost>>(
      future: () async { 
        var doc = await FirebaseFirestore.instance.collection('collectionPath').get();
        var data = doc.docs.map((doc) async => await GeoPost.fromDoc(doc)).toList();
        geoPosts = await Future.wait(data);
        return geoPosts;
      }(),
      builder: (context, snapshot) { }
    
  • 此外,您需要将 getPostUserDataFromFirestore 方法的 return 类型从 Future<void> 更改为 Future<Userdata>void没有值时使用returned.

    getPostUserDataFromFirestore 方法更新为:

    Future<Userdata> getPostUserDataFromFirestore (String did) async {
      return Userdata.fromDoc(await usersRef.doc(uid).get());
    }