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

Flutter实现带自定义凹陷形状的SliverAppBar

实现带自定义凹陷形状的原生SliverAppBar

如果你需要给Flutter的SliverAppBar添加自定义凹陷形状,同时保留它的原生特性(比如滚动收缩、下拉刷新联动等),不用通过SliverPersistentHeaderDelegate重新实现一套,直接通过自定义ShapeBorder就能搞定。

解决方案步骤

  1. 创建自定义ShapeBorder类
    继承ShapeBorder,将你已有的DepressionAppBarClipper的裁剪逻辑迁移到这个类中,重点实现getOuterPath方法来定义凹陷形状的路径:
class AppBarShapeBorder extends ShapeBorder {
  final double depressionRadius; // 控制凹陷的半径

  AppBarShapeBorder({this.depressionRadius = 20.0});

  @override
  EdgeInsetsGeometry get dimensions => EdgeInsets.zero;

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

  @override
  Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
    // 复用自定义裁剪器中的路径逻辑,生成凹陷形状
    final path = Path();
    path.lineTo(rect.left, rect.top);
    path.lineTo(rect.right, rect.top);
    path.lineTo(rect.right, rect.bottom - depressionRadius);
    // 添加底部右侧的凹陷圆弧
    path.arcToPoint(
      Offset(rect.right - depressionRadius, rect.bottom),
      radius: Radius.circular(depressionRadius),
      clockwise: false,
    );
    path.lineTo(rect.left + depressionRadius, rect.bottom);
    // 添加底部左侧的凹陷圆弧
    path.arcToPoint(
      Offset(rect.left, rect.bottom - depressionRadius),
      radius: Radius.circular(depressionRadius),
      clockwise: false,
    );
    path.close();
    return path;
  }

  @override
  void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {
    // 如需额外绘制边框等逻辑,可在此实现
  }

  @override
  ShapeBorder scale(double t) {
    return AppBarShapeBorder(depressionRadius: depressionRadius * t);
  }
}
  1. 在SliverAppBar中应用自定义形状
    直接将AppBarShapeBorder实例赋值给SliverAppBar的shape属性,完全保留原生SliverAppBar的所有特性:
SliverAppBar(
  expandedHeight: 200,
  shape: AppBarShapeBorder(depressionRadius: 30),
  flexibleSpace: FlexibleSpaceBar(
    title: const Text('带凹陷的AppBar'),
    background: Image.network(
      'https://example.com/your-background-image.jpg',
      fit: BoxFit.cover,
    ),
  ),
)

关键说明

  • 这种方式无需替换原生SliverAppBar,完美保留其滚动行为、状态栏适配、Toolbar组件集成等特性。
  • 可根据需求调整AppBarShapeBorder中的路径逻辑,修改凹陷的大小、位置或形状,适配不同设计需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:45:05