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

Flutter中如何根据条件为ListTile设置左侧边框及圆角样式?

Flutter ListTile 按条件设置左侧边框与圆角样式

我需要根据belongsToCluster的值为ListTile设置对应样式:

  • 当belongsToCluster为true时,ListTile的左上角和左下角为圆角,同时左侧带有一条粗色边框
  • 效果参考下图:
    ListTile目标样式

当前我的代码如下:

Color color = Colors.white;

final borderRadius = const BorderRadius.only(
  topLeft: Radius.circular(32),
  bottomLeft: Radius.circular(32),
);

return ListTile(
  tileColor: Colors.indigo[400],

  shape: belongsToCluster
      
          ? RoundedRectangleBorder(
              borderRadius: borderRadius,
              side: BorderSide(width: 10, color: color))
          : Border(
              left: BorderSide(
              color: color,
              width: 10.0,
            ))),
  leading: containedIcon(),
  title: deviceName(),
  // blah blah

解决方案

你的代码存在两个核心问题:

  1. ListTile的shape属性仅接受OutlinedBorder类型(如RoundedRectangleBorder),直接使用Border会导致类型不匹配报错
  2. 当belongsToCluster为false时,未统一使用同类型的边框配置

以下是修正后的代码,完全匹配你的需求:

Color color = Colors.white;

return ListTile(
  tileColor: Colors.indigo[400],
  shape: RoundedRectangleBorder(
    borderRadius: belongsToCluster
        ? const BorderRadius.only(
            topLeft: Radius.circular(32),
            bottomLeft: Radius.circular(32),
          )
        : BorderRadius.zero,
    // 仅保留左侧边框,其余边框设为无
    side: BorderSide(
      width: 10,
      color: color,
      top: BorderSide.none,
      right: BorderSide.none,
      bottom: BorderSide.none,
    ),
  ),
  leading: containedIcon(),
  title: deviceName(),
  // 其他属性
);

如果需要让左侧边框与ListTile的圆角更贴合(避免边框超出圆角范围),可以用ClipRRect包裹ListTile,确保视觉效果一致:

Color color = Colors.white;

return ClipRRect(
  borderRadius: belongsToCluster
      ? const BorderRadius.only(
          topLeft: Radius.circular(32),
          bottomLeft: Radius.circular(32),
        )
      : BorderRadius.zero,
  child: ListTile(
    tileColor: Colors.indigo[400],
    shape: RoundedRectangleBorder(
      borderRadius: belongsToCluster
          ? const BorderRadius.only(
              topLeft: Radius.circular(32),
              bottomLeft: Radius.circular(32),
            )
          : BorderRadius.zero,
      side: BorderSide(
        width: 10,
        color: color,
        top: BorderSide.none,
        right: BorderSide.none,
        bottom: BorderSide.none,
      ),
    ),
    leading: containedIcon(),
    title: deviceName(),
    // 其他属性
  ),
);

内容的提问来源于stack exchange,提问作者Stéphane de Luca

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:20:30