I want to show posts only if they contain number 1 in it.
JSON:
posts = '{"number":"1"}';
JSON is fetched in a separate file like:
Posts(Map<String, dynamic> json) : super(json) {
posts = json["number"];
}
And I have this:
Widget _buildGridView() => StreamBuilder<List<Posts>?>(
builder: (context, snapshot) {
if (snapshot.data != null) {
return new GridView.count(
children: List.generate(snapshot.data!.length, (index) {
return _buildPlacesCell(snapshot.data![index]);
}));
}
});
I am wondering: can I do something like this?
if (snapshot.data.posts.number = 1)
Instead of
snapshot.data != null
Or not?
I want to show my data only if the post has number 1 in it’s JSON file, but I can’t get this to work.
I am getting the following error:
error: The getter 'posts' isn't defined for the type 'List<Post>'
Edit: after Jamiu’s snippet, getting the following errors:
error: The operator ‘[]’ isn’t defined for the type ‘Post’.
and:
error: The body might complete normally, causing ‘null’ to be
returned, but the return type is a potentially non-nullable type
2
Answers
//Try this
You could nest the if statements. First, check if the
snapshot.data != null
and then inside that if statement, check ifsnapshot.data.posts.number = 1
like so:Consider doing this: