ListView.builder() in Flutter with different items

Viewed 94501

Consider the following build() function:

Widget build(BuildContext context){
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ListView.builder(
            itemCount: 6,
              itemBuilder: (context, i){
                if(numberTruthList[i]){
                  return ListTile(
                    title: Text("$i"),
                  );
                }
              },
          ),
        )
      ),
    );
  }

If the numberTruthList is

List<bool> numberTruthList = [true, true, true, true , true, true];

then the output comes out to be

enter image description here

and if the numberTruthList is

List<bool> numberTruthList = [false, true, true, true , true, true];

the output comes out to be

enter image description here

I want the output to be a ListView with the items

 ListTile( title: Text("$i"),);

for values of i such that numberTruthList[i] is true, what should be the code?

3 Answers
ListView.builder(
  itemCount: 6,
  itemBuilder: (context, i) {
    return numberTruthList[i]
      ? ListTile(
          title: Text(numberTruthList[i].toString()),
        )
      : Container(
          height: 0,
          width: 0,
        );
   },
)

use Wrap() in else case.

Container wraps content when there is content and match parent when there are no content.

Wrap wraps the content no matter what.

The itemBuilder should always return a non-null Widget. You can check it here.

Related