I am having an issue with creating a future builder. I am trying to create a List of Documents to show in a ListView but I can not find away to create the List in the custom class I have created(BlogPosts).
I keep receiving this error:
Error: A value of type 'Iterable<BlogPost>' can't be assigned to a variable of type 'List<BlogPost>'.
here is my code:
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')
);
}
}
)
here is the code for my custom 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']
);
}
}
The map()
function returns an Iterable
. To turn that into a list, call toList()
on its result. So:
posts = val.docs.map((doc) => BlogPost.fromDocument(doc)).toList()