How can I show just 5 items of a list in flutter

10,187

Solution 1

To limit an Iterable(List is an Iterable) to n elements, you can use the .take(int count) method.

// A list of 0 - 999 ( 1,000 elements)
var nums = [for(int i = 0; i < 1000; i++) i];
// Take only the first 5, then print
print(nums.take(5));

The Iterable returned is lazy. It doesn't trim the list or anything. It's just an iterator that will only produce at most count values

Additionally, you can use the .skip(int count) method to skip the first count values in the list.

Combine the 2 for something like this:

// skips 0-4, takes 5,6,7,8,9
print(nums.skip(5).take(5));

Solution 2

Use take() this method returns iterable starting from index 0 till the count provided from the given list. here is you have a list with using toList()

var myList = [0, 'one', 'two', 'three', 'four', 'five'];

myList.take(3).toList()  // [0, one, two]

Solution 3

I am not 100% sure what your problem is. If you want to build widgets as you go, you can use ListView.builder widget. Give it an itemBuilder and an optional itemCount. It will build as you go and delete the unseen widgets.

ListView.builder(
    itemCount: myList.length,
    itemBuilder: (context, index) => Card(
      child: ListTile(
        title: Text(myList[index]),
        ),       
      ),
    ),
  ),

Check out this doc

Share:
10,187
Mohammad Hosein
Author by

Mohammad Hosein

Updated on June 09, 2022

Comments

  • Mohammad Hosein
    Mohammad Hosein almost 2 years

    I want to show a list in flutter and I'm using listView. The thing is I just want to show 5 items, by this I mean that When the user scrolls down I want to remove from the beginning index and add another widget to the end of the list that contains my widgets, but when I do that the ScrollView instead of staying where it is(for example showing the item in the index 3) it goes to the next item(it jumps where the item 4 is).

    My data is kinda expensive and I can't keep them I have to remove them from the beginning. I'm really stuck I would really appreciate some help

  • Mohammad Hosein
    Mohammad Hosein over 3 years
    yes you are right, but if i do this it will just keep adding to the list view. imagine a list that contains numbers from 1 to 6. now I want to add number 7 to the list and also remove number 1 so it will be a list of numbers from 2 to 7. The problem is that when I do this the list view that is showing number 4 will show number 5
  • d249u7
    d249u7 over 3 years
    You can solve that by adding a key. Check out this video:youtu.be/…