如何在ListView Flutter中跳过索引

g52tjvyc  于 2023-01-18  发布在  Flutter
关注(0)|答案(3)|浏览(120)

我尝试在Flutter中使用一个简单的ListView。问题是我想为一张卡片使用列表两个索引(索引)。
所以当列表视图扩展时,它应该使用两个索引,第一个卡片可以访问索引1和2的数据,第二个卡片可以访问索引3和4的数据,以此类推。
如果有人知道如何建立这样的东西,我会很感激:)

vsikbqxv

vsikbqxv1#

我觉得有两种方法可以处理这种情况...

第一次

您可以生成其他列表,其中每个元素将包含原始列表的2个元素。

使用isOdd或isEven忽略某些索引。

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

注意不要让索引超出列表的范围

avwztpqn

avwztpqn2#

我就是这么处理的,以防将来有人用得上:

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

除了使用sizedbox size 0之外,肯定有一种更好的方法来设计不存在的小部件,但我对flutter相当陌生,而且它很有效。

w6lpcovy

w6lpcovy3#

也可以这样做:

SizedBox.shrink();

正在保存代码行:)

相关问题