Home > Blockchain >  How to skip an index in an ListView Flutter
How to skip an index in an ListView Flutter

Time:02-18

I'm trying to use a simple ListView in Flutter. The problem is that i want to use two indices (index) of my list for one card.

So if when the ListView is expanding it should always use two indices. The first Card has access to data from index 1 and 2, the second card from 3 and 4 and so on.

If anyone knows how to build something like this I'd appreciate :)

CodePudding user response:

I see 2 ways to handle that situation...

First

You can generate other list where each element will contain 2 elements of the original list.

Second

Use isOdd or isEven to ignore some indexes.

ListView.builder(
  itemCount: myList.length
  itemBuilder: (_, index) {
    if(index.isEven){
       return MyCustomTile(
         first: myList[index]
         second: index   1 == myList.length ? null : myList[index 1]
       );
    }
    return Container();
  }
)

Attention to not get an index out of the bounds of your list

CodePudding user response:

That's how I handled it, in case someone could use it in the future:

ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: itemList.length,
              itemBuilder: (context, index) {
                if (index % 2 == 0 && index < itemList.length) {
                  return Column(
                    children: [
                      ListElementWidget(data: itemList[index]),
                      (index   1 < itemList.length)
                          ? Padding(
                              padding: const EdgeInsets.only(top: 8.0),
                              child: ListElementWidget(
                                  data: itemList[index   1]),
                            )
                          : const SizedBox(
                              width: 0,
                            ),
                    ],
                  );
                } else {
                  return const SizedBox(width: 0);
                }
              },
            ),
          ),

There is definitely a nicer way to design non-existent widgets other than with sizedbox size 0. But I'm fairly new to flutter and it works.

  • Related