Flutter Listview.Separated 在列表的开头和结尾添加分隔符

标签 flutter dart

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

我可以通过伪造 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);
  }))),

最佳答案

恐怕这已经是我们使用 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并将您的项目包装在带有边框底部的容器

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)
          
        )
      )
    ),
  },
);

关于Flutter Listview.Separated 在列表的开头和结尾添加分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62204671/

相关文章:

flutter - 如何从 Streambuilder 订购项目

flutter - 使用MultiPartRequest上传多张图片: Content size below specified contentLength

actionscript-3 - 什么是Dart等同于AS3参数对象?

flutter - 运行时Http包和JsonPlaceholder中的错误

datetime - 如何实际保持DateTime.now()为最新状态?

flutter - build 方法多久被调用一次?

json - 如何在 flutter 中反序列化来自json的对象列表

facebook - 如何通过单击 flutter 应用程序中的按钮自动从 facebook 中的图库发布图像?

flutter - 与 Flutter 共享本地镜像

flutter - 按下后退按钮时如何在后台发送应用程序