Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 956
Mohammad Hosein Avatar asked Sep 08 '20 14:09

Mohammad Hosein


2 Answers

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));
like image 54
loganrussell48 Avatar answered Oct 17 '22 02:10

loganrussell48


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

like image 31
Eren Avatar answered Oct 17 '22 02:10

Eren