繁体   English   中英

Flutter:如何手动向 ListView 添加额外的 ListTile

[英]Flutter: How to add an extra ListTile to ListView manually

我想要做的是在ListView的最后添加一个额外的LisTile但我仍然不明白。 我目前的代码是这样的。

child: ListView.builder(
        itemBuilder: (context, index) {
          if (index == 0) {
            // Add an extra item to the start
            return ListTile(
             ...
            );
          }
          index -= 1;
          final item = _items[index];

          // I want to an extra item here as well
          if (index == _items.length) {
              return ListTile();
          }

          return ListTile(
              ...
          );


        },
        itemCount: _items.length + 2,

上面的方法我已经试过了,还是不行。 有错误。

无效值:不在 0..4 范围内,包括 5

当我将itemCount更改为_items.length + 1 ,它不会显示我想要添加到最后的额外ListTile

如果你想添加到开头和结尾,请检查下面

child: ListView.builder(
        itemBuilder: (context, index) {
          if (index == 0) {
            // Add an extra item to the start
            return ListTile(
             ...
            );
          }
          if (index == _items.length + 1) {
              return ListTile();
          }

          index -= 1;
          final item = _items[index];



          return ListTile(
              ...
          );


        },
        itemCount: _items.length + 2,

你的错误在这里:

itemCount: _items.length + 2,

你应该加一

因为你添加了 2 个元素,最后一次调用你得到 index = list.length + 1,然后你从中减去 1,最后你的长度是 1。

例如,假设您的列表有 5 个元素,因为您有

itemCount: _items.length + 2

Listview 将调用您的 func 7 次,在第 7 次调用中,您的索引为 6,您正在执行索引 =-1,这等于 5,而 5 超出了您的范围。 (你有表格 0 到 4)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM