You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开发:如何实现带分隔线的ListTile与ListView布局

Flutter ListTile 间添加分隔线的实现方法

下面提供几种实用的实现方案,根据你的自定义ruleTile组件情况选择:

方案一:给自定义ruleTile添加底部边框

直接在自定义组件内部添加底部边框,让每个Tile自带分隔线,最后一个Tile可通过参数控制隐藏:

class RuleTile extends StatelessWidget {
  final Rule rule;
  final bool showDivider; // 新增参数控制分隔线显示

  const RuleTile({super.key, required this.rule, this.showDivider = true});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: showDivider 
            ? Border(bottom: BorderSide(color: Colors.grey.shade300, width: 1))
            : null,
      ),
      child: // 原有的Tile内容布局
    );
  }
}

// 使用示例
ListView.builder(
  itemCount: rules.length,
  itemBuilder: (ctx, index) {
    return RuleTile(
      rule: rules[index],
      showDivider: index != rules.length - 1,
    );
  },
)

方案二:使用ListView.separated(官方推荐)

这是Flutter 2.0+提供的专门用于带分隔符列表的API,灵活度最高:

ListView.separated(
  itemCount: rules.length,
  // 构建每个列表项
  itemBuilder: (ctx, index) => RuleTile(rule: rules[index]),
  // 构建分隔符
  separatorBuilder: (ctx, index) => Divider(
    height: 1,
    color: Colors.grey.shade300,
    indent: 16, // 调整缩进与Tile内容对齐
    endIndent: 16,
  ),
)

方案三:在ListView中插入Divider组件

通过ListView.builder在每个Tile后插入Divider,跳过最后一个Tile的分隔线:

ListView.builder(
  itemCount: rules.length,
  itemBuilder: (ctx, index) {
    return Column(
      children: [
        RuleTile(rule: rules[index]),
        if (index != rules.length - 1)
          Divider(
            height: 1,
            color: Colors.grey.shade300,
            indent: 16,
            endIndent: 16,
          ),
      ],
    );
  },
)

方案四:用ListTile.divideTiles包裹

如果你的自定义RuleTile兼容ListTile结构,可直接用官方方法快速生成带分隔线的列表:

ListView(
  children: ListTile.divideTiles(
    context: context,
    color: Colors.grey.shade300,
    tiles: rules.map((rule) => RuleTile(rule: rule)).toList(),
  ).toList(),
)

内容的提问来源于stack exchange,提问作者L.Goyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:10:16