簡體   English   中英

在 ListView 的頂部和底部添加空容器

[英]Add empty container at the top and the bottom of a ListView

我需要在 ListView 的頂部和底部添加一個空容器,以便可以在頂部和底部自動添加分隔線。 這是我的 ListView 構建器 class

      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(索引):無效值:只有有效值是0:1

更新 else 塊的代碼

return itemBuilder(context, items[index-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,
      ),
    );

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM