Is there a way to to show snapshot data based on object value in Dart / Flutter (REST)?

Question

Asked by Johan on November 13, 2021 (source).

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

Answer

Question answered by Jamiu (source).

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:[
                        for(var post in data)
                            if (post.number == '1')  _buildPlacesCell(post);
                    ],
                );
            }else{
                return const Center(
                    Text('No posts to display');
                );
            }
        }
        if (snapshot.hasError) {
            print(snapshot.error);
            //! do any error handling here
        }
        return const Center(child: CircularProgressIndicator());
        },
    ),
DART FLUTTER JSON REST WORDPRESS
SHARE: