Flutter开发:如何在SliverAppBar组件中嵌入Card部件
实现方案
你可以通过修改SliverAppBar的裁剪属性+在flexibleSpace中使用Stack布局的方式实现Card嵌入/突出SliverAppBar的效果,核心修改点如下:
- 给SliverAppBar添加
clipBehavior: Clip.none属性,默认SliverAppBar会裁剪超出自身边界的组件,关闭后才能让Card突出到AppBar下方区域 - 把flexibleSpace的内容换成Stack布局,用Positioned控制Card的位置,将bottom设为负值即可实现Card半挂在AppBar底部的效果
修改后的参考代码如下:
Widget build(BuildContext context) { return SliverAppBar( expandedHeight: 25.h, backgroundColor: celticBlue, // 新增:关闭裁剪,允许内容超出AppBar边界 clipBehavior: Clip.none, actions: [ IconButton( icon: const Icon(Icons.more_vert), onPressed: () {}, ), ], title: Text('Quran', style: whiteHeading16), centerTitle: true, shadowColor: danube, pinned: true, elevation: 1, shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.elliptical(100, 50), bottomRight: Radius.elliptical(50, 100), ), ), flexibleSpace: FlexibleSpaceBar( background: Stack( children: [ // 这里可以放你原本flexibleSpace里的其他背景内容 Positioned( left: 25, right: 25, // 调整这个负值控制Card突出的高度 bottom: -10.h, child: Card( elevation: 4, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), child: SizedBox( height: 15.h, // 这里放你Card内部的内容 child: const Center(child: Text("Card内容")), ), ), ) ], ), ), ); }
额外注意:如果你的SliverAppBar是放在CustomScrollView里,记得给CustomScrollView的slivers列表里第一个SliverAppBar之后,预留足够的顶部间隔,避免后续的内容和突出的Card重叠,比如可以加一个SliverToBoxAdapter(child: SizedBox(height: 12.h))作为间隔。
内容的提问来源于stack exchange,提问作者Naufal Rajabi
相关产品推荐
相关产品推荐

