如何在Flutter的SliverAppBar中居中FlexibleSpaceBar并设置高度
解决方案
关键调整点
- 控制
SliverAppBar的toolbarHeight和expandedHeight在64-68区间,确保折叠/展开的高度符合需求 - 调整
FlexibleSpaceBar的titlePadding消除默认内边距,让内容完全居中 - 通过嵌套布局确保搜索栏及右侧按钮整体居中,同时控制搜索容器的高度
- 保留
pinned: true实现滚动折叠效果,配合floating和snap实现快速展开
修改后的完整代码
class _ArticleAppBarState extends State<ArticleAppBar> with SingleTickerProviderStateMixin{ Route _searchPageRoute(){ return PageRouteBuilder( transitionsBuilder: (context, animation, secondaryAnimation, child) { const Offset begin = Offset(0.0, 1.0); const Offset end = Offset.zero; const Cubic curves = Curves.easeInOut; Animatable<Offset> tween = Tween(begin: begin, end: end).chain(CurveTween(curve: curves)); return SlideTransition(position: animation.drive(tween)); }, pageBuilder: (context, animation, secondaryAnimation) { return const SearchArticlesPage(); }, ); } @override Widget build(BuildContext context) { // 定义目标高度区间内的数值 const appBarHeight = 66; return SliverAppBar( expandedHeight: appBarHeight.toDouble(), toolbarHeight: appBarHeight.toDouble(), // 折叠后高度与展开一致,也可设为64实现渐变折叠 centerTitle: true, forceElevated: true, flexibleSpace: FlexibleSpaceBar( // 消除默认title内边距,让内容完全居中 titlePadding: EdgeInsets.zero, title: SizedBox( height: appBarHeight.toDouble(), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, // 整体居中 children: [ Expanded( flex: 8, // 调整搜索栏占比,避免按钮挤压 child: GestureDetector( onTap: () => Navigator.of(context).push(_searchPageRoute()), child: Container( height: 48, // 控制搜索栏自身高度 decoration: BoxDecoration( borderRadius: BorderRadius.circular(kDefaultRoundedValue), color: Colors.blueGrey.shade700.withOpacity(.20), ), child: const Row( mainAxisAlignment: MainAxisAlignment.start, children: [ SizedBox(width: 12), // 增加左侧间距优化布局 Icon(Icons.search_rounded), SizedBox(width: 8), Expanded( child: Text("Search"), ) ], ), ), ) ), const SizedBox(width: 8), IconButton( onPressed: () { }, icon: const Icon(Icons.table_rows_rounded) ) ], ), ), ), floating: true, pinned: true, snap: true, ); } }
细节说明
- 高度控制:通过
expandedHeight和toolbarHeight统一设置为66(在64-68区间内),如果需要折叠时高度略有变化,可将toolbarHeight设为64,expandedHeight设为68,实现平滑的高度过渡 - 居中处理:
FlexibleSpaceBar设置titlePadding: EdgeInsets.zero,消除默认的底部内边距,避免内容偏上/偏下- 外层用
SizedBox固定高度,配合Row的mainAxisAlignment: MainAxisAlignment.center让整体内容居中
- 搜索栏优化:给搜索容器设置固定高度
48,同时增加左右间距,提升视觉体验;通过flex属性调整搜索栏与右侧按钮的占比,避免布局挤压 - 折叠效果:
pinned: true确保滚动时AppBar保持顶部并折叠,floating和snap组合实现向上滚动折叠、向下滚动快速展开的交互
内容的提问来源于stack exchange,提问作者KueCubit
相关产品推荐
相关产品推荐

