Narrowly related to this question:
How to fetch only items from JSON if certain object value is there
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:
Place(Map<String, dynamic> json) : super(json) {
posts = json["number"];
}
And I have this:
Widget _buildGridView() => StreamBuilder<List<Place>?>(
stream: listPosts,
initialData: [],
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<Place>'
Edit: after Jamiu's snippet, getting the following errors:
error: The operator '[]' isn't defined for the type 'Place'.
and:
error: The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type
Edit after your last update:
Now this has become a problem in a different widget:
error: Undefined name 'context'.
And:
onTap: () {
HomeNav(context).open;
},
CodePudding user response:
//Try this
Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
if(data["number"]=="1"){
//do
}
CodePudding user response:
You could nest the if statements. First, check if the snapshot.data != null
and then inside that if statement, check if snapshot.data.posts.number = 1
like so:
if(snapshot.data!=null){
if(snapshot.data.posts.number=1){
return new GridView.count(
children: List.generate(snapshot.data!.length, (index) {
return _buildCell(snapshot.data![index]);
}));
}
}
Consider doing this:
StreamBuilder<List<Place>>(
stream: listPosts,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasData) {
final data = snapshot.data!;
if (data.isNotEmpty) {
return GridView.count(
children: List.generate(
data.length,
(index) {
if (data[index].number == '1') {
return _buildPlacesCell(data[index]);
} else {
return Visibility(
visibile: false
child: const SizedBox();
);
}
},
),
);
}else{
return Visibility(
visible: false
child: const SizedBox();
);
}
}
if (snapshot.hasError) {
print(snapshot.error);
//! do any error handling here
}
return const Center(child: CircularProgressIndicator());
},
),