Flutter SliverAppBar返回按钮异常:可点击但无法显示
问题分析
你的问题根源在于TabBarWidget的preferredSize计算错误,导致其顶部Container与SliverAppBar的主体区域重叠:
- 你设置的
preferredSize为Size.fromHeight(kToolbarHeight + height),但实际build的子组件高度是120(顶部Container) + kToolbarHeight(TabBar),两者高度不匹配。 - 当
_tabController.index == 0时,传入的height为180,此时preferredSize的高度远大于实际子组件高度,导致TabBarWidget的布局向上延伸,覆盖了SliverAppBar的leading区域。 - 由于顶部Container的颜色和SliverAppBar的
backgroundColor都是AppColors.primaryColor,而返回按钮是白色,视觉上按钮被同色容器遮挡,无法看见。
解决方案
修正TabBarWidget的preferredSize计算逻辑,使其与实际子组件高度一致,并根据传入的height参数控制顶部Container的显示:
class TabBarWidget extends StatelessWidget with PreferredSizeWidget { const TabBarWidget( {Key? key, required this.tabController, required this.tabs, this.onTap, required this.height}) : super(key: key); final TabController tabController; final double height; final List<Widget> tabs; final ValueChanged<int>? onTap; @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, children: [ // 根据height参数控制顶部Container是否显示 if (height > 0) Container( height: 120, decoration: const ShapeDecoration( color: AppColors.primaryColor, shape: CustomShapeBorder(180), ), ), Container( color: Colors.white, child: TabBar( controller: tabController, labelColor: AppColors.boldRedColor, onTap: onTap, unselectedLabelStyle: const TextStyle( color: Colors.grey, fontWeight: FontWeight.bold, ), labelStyle: const TextStyle( fontWeight: FontWeight.bold, color: AppColors.boldRedColor, ), unselectedLabelColor: Colors.grey, indicatorColor: AppColors.boldRedColor, tabs: tabs, ), ), ], ); } @override Size get preferredSize => Size.fromHeight( // 实际高度 = 显示Container时的120 + TabBar默认高度kToolbarHeight (height > 0 ? 120 : 0) + kToolbarHeight, ); }
额外优化建议
如果你的height参数是用来控制顶部Container的高度,可以直接将Container的height设置为height,更符合参数语义:
// 替换build中的顶部Container if (height > 0) Container( height: height, // 直接使用传入的height参数 decoration: const ShapeDecoration( color: AppColors.primaryColor, shape: CustomShapeBorder(180), ), ), // 对应的preferredSize Size get preferredSize => Size.fromHeight( (height > 0 ? height : 0) + kToolbarHeight, );
调整后,SliverAppBar的bottom区域高度与实际内容高度匹配,不会再覆盖leading按钮,白色返回按钮就能正常显示。
内容的提问来源于stack exchange,提问作者FadyFouad
相关产品推荐
相关产品推荐

