Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I limit the number of items in my ListView.builder?

I want to limit the itemCount of my ListView to a maximum of 5 and add the text "and more" if there are more items and only display the items if they are 5 or less. I've tried using itemCount: 5 but that returns an error when the items are less than 5. How can I implement this?

ListView.builder(
              shrinkWrap: true,
              itemCount: features.length,
              itemBuilder: (context, index) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        "•  ${features[index]}",
                        style: TextStyle(fontWeight: FontWeight.bold),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                );
              }),
like image 449
osodo Avatar asked Sep 01 '25 04:09

osodo


2 Answers

itemCount: features.length < 5 ? features.length : 5,
like image 199
Muhammad Tameem Rafay Avatar answered Sep 02 '25 19:09

Muhammad Tameem Rafay


Please try this

ListView.builder(
              shrinkWrap: true,
              itemCount: features.length=>5?5:features.length,
              itemBuilder: (context, index) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        "•  ${features[index]}",
                        style: TextStyle(fontWeight: FontWeight.bold),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                );
              }),
like image 45
Jahidul Islam Avatar answered Sep 02 '25 18:09

Jahidul Islam