Search code examples
dartfluttermaterial-design

ListView.builder() in Flutter with different items


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?


Solution

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