Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 568
Naveen Avatar asked Jan 12 '19 21:01

Naveen


People also ask

How do I separate ListView in Flutter?

This constructor is ListView.ListView. separated creates a fixed-length, scrollable , linear array of list “items” separated by list item “separators”. The itemBuilder callback is called whenever there are indices ≥ 0 and< itemCount .

How do you add a list item dynamically in Flutter?

Let us add a TextField to add a list item to the list dynamically. Run this application, and you should see a TextField widget and a Add button to add an item to the list dynamically. Type in some name and click on Add button. The item will be added at the top of the list dynamically.

What is the difference between ListView and ListView builder and two properties of ListView builder in Flutter?

ListView() constructor takes argument children where you can use map method of your list to create a list of widgets. These widgets are rendered immediately when the build method is called. ListView. builder() on the other hand, takes itemBuilder and itemCount parameters.


1 Answers

ListView.builder(
  itemCount: 6,
  itemBuilder: (context, i) {
    return numberTruthList[i]
      ? ListTile(
          title: Text(numberTruthList[i].toString()),
        )
      : Container(
          height: 0,
          width: 0,
        );
   },
)
like image 94
westdabestdb Avatar answered Oct 18 '22 15:10

westdabestdb