skip to Main Content

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


  1. //Try this

    Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
    if(data["number"]=="1"){
       //do
    }
    
    Login or Signup to reply.
  2. 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());
            },
        ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search