Flutter - ListView.builder - 我们可以在 "index" 旁边添加一个变量用作 "counter" 吗?

Flutter - ListView.builder - can we add a variable to use as "counter" beside "index"?

我的问题似乎表述不当,但我找不到更清晰的表达方式。 情况是这样的:

有没有办法添加另一个“计数器”?我可以使用它来代替“索引”,它实际上对应于显示的元素数量?

代码如下:

ListView.builder(
            cacheExtent: 2000,
            padding: const EdgeInsets.all(20),
            itemCount: uD.userInfo.carnetList.length,
            itemBuilder: (context, index) {
              return uD.userInfo.carnetList[index].thematic == false
                  ? CarnetListCard2(
                      index: index,  **// This is where I used Index to display "List n+$index" in the widget.** 
                      taille: uD.userInfo.carnetList[index].carnetWordId.length,
                      titre: uD.userInfo.carnetList[index].titre,
                      dateCreation: uD.userInfo.carnetList[index].creation,
                      dateModification:
                          uD.userInfo.carnetList[index].modification,
                      test: uD.userInfo.carnetList[index].test,
                      dateTest: uD.userInfo.carnetList[index].testDate,)                             
                  : Container();
            },
          ),

你很接近,但你不想在项目构建期间过滤列表。如果您确保在将列表传递给列表视图之前对其进行过滤,您将获得所需的结果。最简单的方法:

final list = D.userInfo.carnetList.where((carnet) => !carnet.thematic).toList();

return ListView.builder(
 itemCount: list.length,
 itemBuilder: (context, index) {
   final carnet = list[index];
   final number = index + 1;
   ...
 }
)

或者如果您不想使用单独的列表

ListView(
  children: D.userInfo.carnetList.where((carnet) => !carnet.thematic).map((item) {
   return ... // your widget
 }).toList();
);

您也可以使用计数器,只要条件为真,就增加它。

它将作为 index of the items that are actually good for me

int _itemsCounter = 0;

ListView.builder(
            cacheExtent: 2000,
            padding: const EdgeInsets.all(20),
            itemCount: uD.userInfo.carnetList.length,
            itemBuilder: (context, index) {
              if (uD.userInfo.carnetList[index].thematic == false) _itemsCounter++;

              return uD.userInfo.carnetList[index].thematic == false
                  ? CarnetListCard2(
                      index: index,  **// This is where I used Index to display "List n+$index" in the widget.** 
                      taille: uD.userInfo.carnetList[index].carnetWordId.length,
                      titre: uD.userInfo.carnetList[index].titre,
                      dateCreation: uD.userInfo.carnetList[index].creation,
                      dateModification:
                          uD.userInfo.carnetList[index].modification,
                      test: uD.userInfo.carnetList[index].test,
                      dateTest: uD.userInfo.carnetList[index].testDate,)                             
                  : Container();
            },
          ),

只要确保在使用 _itemsCounter 作为索引时,从中减去 1。

所以如果有3个项目满足条件,这个计数器就是3,但是元素的索引是0,1,2