Future builder flutter firebase error: A value of type 'Iterable<BlogPost>' can't be assigned to a variable of type 'List<BlogPost>'

Future builder flutter firebase error: A value of type 'Iterable<BlogPost>' can't be assigned to a variable of type 'List<BlogPost>'

我在创建未来构建器时遇到问题。我正在尝试创建一个文档列表以在 ListView 中显示,但我找不到在我创建的自定义 class 中创建列表(BlogPosts)。

我一直收到这个错误:

Error: A value of type 'Iterable<BlogPost>' can't be assigned to a variable of type 'List<BlogPost>'.

这是我的代码:

CollectionReference postsRef = FirebaseFirestore.instance.collection('posts');
late List<BlogPost> posts;

FutureBuilder(
          future: postsRef.get().then((val) {
              posts = val.docs.map((doc) => BlogPost.fromDocument(doc));
            }),
          builder: (context, snap) {
            if(snap.connectionState == ConnectionState.done) {
              return ListView.builder(
                physics: BouncingScrollPhysics(),
                  itemCount: 3,
                  itemBuilder: (context, index) {
                  return Text('data);
                  }
              );
            } else {
              return Center(
                child: Text('Loading')
              );
            }
          }
        )

这是我的自定义代码 class:

class BlogPost {
  String displayName;
  String postmsg;
  String postId;
  String UserId;

  BlogPost(this.displayName, this.postmsg, this.postId, this.UserId);

  factory BlogPost.fromDocument(DocumentSnapshot doc) {
    return BlogPost(
        doc['displayName'],
        doc['postmsg'],
        doc['postId'],
        doc['UserId']
    );
  }
}

map() function returns 一个 Iterable。要将其转换为列表,请对其结果调用 toList()。所以:

posts = val.docs.map((doc) => BlogPost.fromDocument(doc)).toList()