Home > Software engineering >  Assigning specific items in ListViewBuilder for certain values of index
Assigning specific items in ListViewBuilder for certain values of index

Time:02-21

I have implemented a standard ListViewBuilder. My objective is to set some properties according to the index, for example if the index is equal to (item count - 1), i.e end of the list, i want Text to be displayed, i haven't been able to do that. Any help is appreciated. Here is my Code:

              Container(
                        height: 500,
                        width: double.infinity,
                        child: ListView.builder(
                          itemCount: 6,
                          padding: EdgeInsets.symmetric(vertical: 0.0),
                          itemBuilder: (context, index) {
                            if (index <= 5) {
                              return ListCard().buildListCard();
                            }
                            return Container(
                                child: Text("FIN"),
                                height: 50,
                                width: double.infinity);
                          },
                        ),
                      )

Output Image

CodePudding user response:

Let's going your example, if you want to show the Text widget on the list end you can follow below lines;

              Container(
                        height: 500,
                        width: double.infinity,
                        child: ListView.builder(
                          itemCount: dynamicList.length,
                          padding: EdgeInsets.symmetric(vertical: 0.0),
                          itemBuilder: (context, index) {
                            if (index <= 5) {
                              return ListCard().buildListCard();
                            }
                            if (index == dynamicList.length - 1) { // <-- this line your want logic
                              return Text('Your text widget'); 
                            }

                            return Container(
                                child: Text("FIN"),
                                height: 50,
                                width: double.infinity);
                          },
                        ),
                      )

CodePudding user response:

You have incorrectly logic in your code. Remember that index is starting from 0. So, the following code:

// From index 0 to index 5 (6 item)
if (index <= 5) {

}

will always executed because it is included all your items which is 6 in length.

So, change it to:

// From index 0 to index 4 excluding the 5.
if (index < 5) {

}
  • Related