Mohammad Hosein
Mohammad Hosein

Reputation: 495

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

Upvotes: 16

Views: 28593

Answers (4)

Filip Wajs
Filip Wajs

Reputation: 31

Better works:

list1=list.sublist(0,5);

it limits list to first 5 elements.

Upvotes: 1

Kyo97
Kyo97

Reputation: 11

itemCount: 5, <<this will max your list

if your list less than 5 it will have error, so simply used this:

int limit_transaction = 0;

then in your FutureBuilder: builder: (context, snapshot) {

if (snapshot.hasData) {
 List<LastTransaction> list = snapshot.data;
    if(list.length == 1){
        limit_transaction = 1;
    } else if(list.length == 2){
        limit_transaction = 2;
    } else if(list.length == 3){
        limit_transaction = 3;
    } else if(list.length == 4){
        limit_transaction = 4;
    } else if(list.length == 5){
        limit_transaction = 5;
    }

Last Step in Listview, just parse this:

itemCount: limit_transaction,

Upvotes: 0

user14037074
user14037074

Reputation:

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

Upvotes: 1

loganrussell48
loganrussell48

Reputation: 1864

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));

Upvotes: 38

Related Questions