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

Flutter:如何移除组件部分区域并添加外圈提升徽章可见性

Flutter实现带镂空效果的醒目徽章

要实现你需要的效果,核心是给目标组件(灰色Container/图片/按钮等)在徽章位置挖去圆形区域露出背景,再通过叠层添加徽章的边框和圆点。具体实现步骤如下:

1. 自定义裁剪器实现组件镂空

通过CustomClipper给目标组件裁剪出右上角的圆形镂空,让背景色透出来:

class BadgeHoleClipper extends CustomClipper<Path> {
  final double holeRadius;

  BadgeHoleClipper(this.holeRadius);

  @override
  Path getClip(Size size) {
    final path = Path()
      // 先绘制组件的完整矩形区域
      ..addRect(Rect.fromLTWH(0, 0, size.width, size.height))
      // 在右上角添加一个圆形区域,通过evenOdd填充模式实现挖洞
      ..addOval(Rect.fromCircle(
        center: Offset(size.width, 0),
        radius: holeRadius,
      ))
      ..fillType = PathFillType.evenOdd;
    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}

2. 用Stack构建完整布局

通过Stack层级实现镂空组件、徽章边框、圆点的叠加,保证视觉效果:

// 假设父容器背景为深蓝色
Scaffold(
  backgroundColor: Colors.deepBlue,
  body: Center(
    child: Stack(
      clipBehavior: Clip.none,
      children: [
        // 被镂空的目标组件(这里用灰色Container,可替换为图片/按钮等)
        ClipPath(
          clipper: BadgeHoleClipper(12), // 镂空半径与徽章边框匹配
          child: Container(
            height: 70,
            width: 250,
            color: Colors.grey,
          ),
        ),
        // 徽章外层边框(稍大的圆圈)
        Positioned(
          top: -8,
          right: -8,
          child: ClipOval(
            child: Container(
              width: 24, // 比绿色圆点大4px,形成边框效果
              height: 24,
              color: Colors.white, // 边框颜色可根据需求调整
            ),
          ),
        ),
        // 核心绿色圆点/计数器
        Positioned(
          top: -8,
          right: -8,
          child: ClipOval(
            child: Container(
              width: 20,
              height: 20,
              color: Colors.green,
              // 如果是计数器,可添加Text组件
              // child: Center(child: Text("3", style: TextStyle(color: Colors.white, fontSize: 12))),
            ),
          ),
        ),
      ],
    ),
  ),
);

关键说明

  • 镂空裁剪器的holeRadius要与徽章边框的半径一致(边框宽24则半径12),确保镂空区域刚好匹配边框大小。
  • 目标组件可以替换为任意Widget(图片、按钮等),只需要给它套上ClipPath即可实现相同的镂空效果。
  • 通过clipBehavior: Clip.none允许徽章超出Stack范围,实现右上角悬浮的视觉效果。

内容的提问来源于stack exchange,提问作者Benjamin Sx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:30:40