我在创建未来构建器时遇到问题。我正在尝试创建一个文档列表以在 ListView 中显示,但我找不到在我创建的自定义类(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 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']
);
}
}
答案 0 :(得分:1)
map()
function 返回 Iterable
。要将其转换为列表,请对其结果调用 toList()
。所以:
posts = val.docs.map((doc) => BlogPost.fromDocument(doc)).toList()