【问题标题】:Listview.builder creating duplicate items on flutterListview.builder 在颤振上创建重复项目
【发布时间】:2020-07-13 19:27:21
【问题描述】:

我正在创建一个小部件的动态列表,但是每次我添加另一个小部件时,它都会重复,当我添加 2 项时,它会变成 4,当我添加 3 时,它会变成 9,依此类推......我'一直在网上搜索可能的原因,我认为它与Flutter JSON duplicate index 非常相似我想我在这段代码中遗漏了一些东西,我不知道把 r 放在哪里,请帮忙

child: Container(
      height: 250,
      child: new ListView.builder(
          physics: ClampingScrollPhysics(),
          shrinkWrap: true,
          scrollDirection: Axis.horizontal,
          itemCount: newList.length,
          itemBuilder: (context, index) {

            final r = newList[index];

            return new Row(
              children: newList,
            );
          }),
    ),
  );

这是我的 delared newList:

List<Widget> newList = [];

【问题讨论】:

    标签: listview flutter dynamic duplicates widget


    【解决方案1】:

    您将列表的 itemCount 设置为 newList 长度。itemBuilder 代码运行 x 次长度。因此,在 itemBuilder 中,您需要将索引传递给您正在显示的 newList,否则它将显示所有列表。

    child: Container(
              height: 250,
              child: new ListView.builder(
                  physics: ClampingScrollPhysics(),
                  shrinkWrap: true,
                  scrollDirection: Axis.horizontal,
                  itemCount: newList.length,
                  itemBuilder: (context, index) {
    
                    final r = newList[index];
    
                    return new Row(
                      children: newList[index],
                    );
                  }),
            ),
          );
    

    【讨论】:

    • 感谢您对此进行调查,我尝试使用您的代码,但显示无法将参数类型“Widget”分配给参数类型“List
    • 这是因为 Row 需要一个小部件列表,而您在 newList 索引中拥有的是单个小部件,例如 SizedBox()、Container()。尝试删除 Row 并返回 newList[index];
    • 如果你想追求 Row 试试这个:return Row(children: [ newList[index] , ] );
    猜你喜欢
    • 1970-01-01
    • 2019-03-11
    • 2020-07-11
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多