14

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?

Marcel Hofgesang
  • 951
  • 1
  • 15
  • 36
Naveen
  • 1,363
  • 7
  • 17
  • 28

4 Answers4

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

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.

Saahithyan Vigneswaran
  • 6,841
  • 3
  • 35
  • 45
0

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

Ivan Aracki
  • 4,861
  • 11
  • 59
  • 73
0

In the body, we have ListView.builder with itemcount 20 and itemBuilder which will create a new widget again and again up to 20 times because we have itemCount=20. If we don't use itemCount in ListView.builder then we will get infinite list items so it is recommended to use itemCount to avoid such mistakes.

import 'package:flutter/material.dart';

const int itemCount = 20;

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: itemCount,
      itemBuilder: (BuildContext context, int index) {
        return ListTile(
          title: Text('Contact ${(index + 1)}'),
          leading: const Icon(Icons.person_outline_rounded),
          trailing: const Icon(Icons.select_all_rounded),
          onTap: () {
            debugPrint('Contact ${(index + 1)}');
          },
        );
      }
    );
  }
}