【问题标题】:Add empty container at the top and the bottom of a ListView在 ListView 的顶部和底部添加空容器
【发布时间】:2020-10-14 12:57:56
【问题描述】:

我需要在 ListView 的顶部和底部添加一个空容器,以便可以在顶部和底部自动添加分隔线。这是我的 ListView 构建器类

      ListView.separated(
        itemCount: items.length + 2,
        padding: EdgeInsets.only(top: 10),
        itemBuilder: (context, index) {
          print(index); //<= print 0 1 2
          if (index == 0 || index > items.length) { //<= here is problem
            return Container();
          } else {
            return itemBuilder(context, items[index]);
          }
        },
        separatorBuilder: (BuildContext context, int index) =>
            separator == null ? Container() : separator)

这应该可以,但是当我尝试将索引与 0 进行比较时它给了我错误

RangeError(index):无效值:只有有效值是0:1

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    我试过你的代码,它工作正常。也许你应该检查 items[] 是否为空

      @override
      Widget build(BuildContext context) {
        var items = [1];
        return ListView.separated(
          itemCount: items.length + 2,
          padding: EdgeInsets.only(top: 10),
          itemBuilder: (context, index) {
            print(index);
            if (index == 0 || index > items.length) {
              return Container(
                height: 50,
                color: Colors.pink,
              );
            } else {
              return Container(
                height: 50,
                color: Colors.blue,
              );
            }
          },
          separatorBuilder: (BuildContext context, int index) => Container(
            height: 50,
            color: Colors.green,
          ),
        );
    

    【讨论】:

    • 是的..但它不适用于项目生成器..查看错误所在的答案
    【解决方案2】:

    为 else 块更新你的代码

    return itemBuilder(context, items[index-1]);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      • 2020-10-10
      • 2012-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多