Conditional ListView.builder

Viewed 4183
return ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (BuildContext context, int index) {
                          final bool alreadySaved =
                              _saved.contains(snapshot.data[index]);
                          if (!snapshot.data[index].isParliamentary) {
                            return ListTile(
                              title: Text(snapshot.data[index].name,
                                  style: TextStyle(
                                    fontSize: 20.0,
                                    fontWeight: FontWeight.bold,
                                  )),
                              trailing: Icon(
                                alreadySaved
                                    ? Icons.favorite
                                    : Icons.favorite_border,
                                color: alreadySaved ? Colors.red : null,
                              ),
                              onTap: () {
                                setState(() {
                                  if (alreadySaved) {
                                    _saved.remove(snapshot.data[index]);
                                    print(_saved);
                                  } else {
                                    _saved.add(snapshot.data[index]);
                                    print(_saved);
                                  }
                                });
                              },
                            );
                          }
                        });

Trying to make a conditional ListView.builder with the boolean statement 'isParliamentary' in my JSON file. The objects with 'isParliamentary' value of 'false' does not show up at all. Do I need an else statement?

2 Answers

I accomplish this by returning a SizedBox(height: 0); When I try just returning null, my index stops once the null is triggered and the list stops.

I have also same problem for break ListView.builder but i don't get any proper solution, i have try below code to handle the conditional ListView

ListView.builder(
    itemCount: snapshot.data.length,
    itemBuilder: (BuildContext context, int index) {
       final bool alreadySaved = _saved.contains(snapshot.data[index]);
       if (!snapshot.data[index].isParliamentary) {
           // Return Widget for this condition, 
       }
       else{
          // Return else widget
          // if you don't have else widget the return null like below
          // return null;
       }
)

I have try this solution it is working fine not get any error.

Related