【问题标题】:Flutter Listview.Separated add Separator at beginning and end of listFlutter Listview.Separated 在列表的开头和结尾添加分隔符
【发布时间】:2020-09-24 00:43:50
【问题描述】:

使用颤振,不仅在行之间放置分隔符,而且作为第一行和最后一行放置分隔符的最简单和最干净的方法是什么?

我可以通过伪造itemCount 并添加额外的行来做到这一点。

...
child: ListView.separated(
  // Offset itemCount to start with separator
  itemCount: sortedList.length + 2,
  itemBuilder: (context, index) {
    if (index == 0) {
      return SizedBox(height: 0.0);
    }
    if (index == sortedList.length + 1) {
      return SizedBox(height: 0.0);
    }
    return ListItem(...);
  },
  separatorBuilder: (context, index) {
    return SizedBox(height: 10.0);
  }))),

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以将您的ListView.serarated 包装在另一个ListView 中,然后将您的分隔线放在ListView.separated 之前和之后。但是您需要定义scrollDirectionshrinkWrap,如示例所示。否则,您将收到无限高的错误。作为分隔符,我使用了 Divider-Widget,但你可以使用任何你想要的。

    ListView(
            children: <Widget>[
              Divider(),
              ListView.separated(
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemBuilder: // ...
                separatorBuilder: // ...
                itemCount: // ...
              ),
              Divider(),
            ],
          ),
    

    【讨论】:

    • 是的,这是另一种方法,但在性能方面是不是完全矫枉过正?
    • 是的,没错。我发现了别的东西,看第一个答案,然后向下滚动到“在最后一项之后添加分隔符”:stackoverflow.com/questions/50687633/…
    【解决方案2】:

    恐怕这是我们用ListView.separated 得到的最干净的东西

    ListView.separated(
      separatorBuilder: (context, index) => const Divider(height: 1.0,),
      itemCount: 2 + boardList.length,
      itemBuilder: (context, index) {
        if (index == 0 || index == boardList.length + 1) return const SizedBox.shrink();
        return MenuItem(
          board: boardList[index - 1], 
          isSelected: boardList[index].id == selectedBoardId
        );
      },
    );
    

    另一种方法是使用ListView.builder 并将您的项目包装为container,底部有边框

    ListView.builder(
      itemCount: boardList.length,
      itemBuilder: (context, index) {
        return Container(
          decoration: BoxDecoration(
            color: (widget.isSelected) ? Colors.grey[50] : color,
            border: Border(
              top: (index == 0) ? BorderSide(color: Theme.of(context).dividerColor) : BorderSide.none
              bottom: BorderSide(color: Theme.of(context).dividerColor)
              
            )
          )
        ),
      },
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多