1

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

Root
  • 25
  • 6

3 Answers3

2

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

Firus
  • 537
  • 1
  • 5
  • 18
1

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.

Root
  • 25
  • 6
1

Also possible is to do this:

SizedBox.shrink();

Saving code lines :)

Viktor
  • 25
  • 6
  • While it’s acceptable to provide code-only answers, it’s often more useful for the community if you can also provide an explanation of the code and help people understand why it addresses the problem. That often reduces the amount of follow-up questions, and can really help new developers understand the underlying concepts. – Sambhav jain Jan 17 '23 at 10:31