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

Flutter中实现带菱形侧边的Container组件方法求助

Flutter 实现带菱形侧边的自定义高度容器

可以通过自定义裁剪路径(ClipPath)或者自定义ShapeBorder来实现需求,两种方式都能让容器高度自由调整,同时保持左右两侧的菱形样式:

方法一:使用 ClipPath + CustomClipper

通过裁剪容器边缘实现菱形侧边,代码直观易调整:

class DiamondSideClipper extends CustomClipper<Path> {
  final double diamondWidth; // 菱形向外突出的宽度

  DiamondSideClipper({this.diamondWidth = 20.0});

  @override
  Path getClip(Size size) {
    final path = Path();
    // 绘制左侧菱形边缘
    path.moveTo(diamondWidth, 0);
    path.lineTo(0, size.height / 2);
    path.lineTo(diamondWidth, size.height);
    // 绘制右侧菱形边缘
    path.lineTo(size.width - diamondWidth, size.height);
    path.lineTo(size.width, size.height / 2);
    path.lineTo(size.width - diamondWidth, 0);
    path.close();
    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
    return oldClipper is DiamondSideClipper && oldClipper.diamondWidth != diamondWidth;
  }
}

// 使用示例
ClipPath(
  clipper: DiamondSideClipper(diamondWidth: 30),
  child: Container(
    height: 120, // 自定义高度
    color: Colors.blueAccent,
    alignment: Alignment.center,
    child: const Text("带菱形侧边的容器"),
  ),
)

方法二:使用 ShapeDecoration + 自定义 ShapeBorder

将菱形形状作为容器装饰,更符合Flutter组件设计习惯:

class DiamondSideShape extends ShapeBorder {
  final double diamondWidth;

  DiamondSideShape({this.diamondWidth = 20.0});

  @override
  EdgeInsetsGeometry get dimensions => EdgeInsets.zero;

  @override
  Path getInnerPath(Rect rect, {TextDirection? textDirection}) => getOuterPath(rect);

  @override
  Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
    final path = Path();
    path.moveTo(rect.left + diamondWidth, rect.top);
    path.lineTo(rect.left, rect.center.dy);
    path.lineTo(rect.left + diamondWidth, rect.bottom);
    path.lineTo(rect.right - diamondWidth, rect.bottom);
    path.lineTo(rect.right, rect.center.dy);
    path.lineTo(rect.right - diamondWidth, rect.top);
    path.close();
    return path;
  }

  @override
  void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {}

  @override
  ShapeBorder scale(double t) => DiamondSideShape(diamondWidth: diamondWidth * t);
}

// 使用示例
Container(
  height: 180, // 自定义高度
  decoration: ShapeDecoration(
    color: Colors.green,
    shape: DiamondSideShape(diamondWidth: 25),
  ),
  alignment: Alignment.center,
  child: const Text("自定义形状容器"),
)

说明

  • diamondWidth 参数控制菱形向外突出的宽度,可根据需求调整
  • 容器高度可任意设置,菱形会自动适配高度,保持对称样式
  • 两种方法都支持添加padding、margin等常规容器属性,不影响原有布局逻辑

内容的提问来源于stack exchange,提问作者Anxo Gómez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:47:35