Flutter中GetX修改PreferredSizeWidget的preferredSize不生效问题求助
问题原因
AppBar 仅在首次构建时会读取 bottom 组件的 preferredSize 计算自身高度,后续 preferredSize 发生变化时 AppBar 不会主动触发重算,只有页面整体刷新重建 AppBar 时才会更新高度,这就是切换页面时高度不生效、刷新后才正常的根本原因。
解决方案
方案1:用响应式状态包裹整个AppBar(最简单)
在使用 BottomOfAppBar 的页面,将整个 AppBar 放到 Obx 中监听状态变化,状态更新时强制 AppBar 整体重建,触发高度重算:
// 页面的Scaffold部分 Scaffold( // 用Obx包裹整个AppBar appBar: Obx(() => AppBar( title: const Text("你的页面标题"), // 其余AppBar配置保持不变 bottom: BottomOfAppBar( tabs: yourTabList, controller: yourTabController, ), )), // 其余页面代码不变 )
方案2:直接控制bottom是否显示(更高效)
如果TabBar禁用时不需要保留任何底部组件,可以直接在状态为false时把AppBar的bottom设为null,不需要通过preferredSize设置0高度:
Scaffold( appBar: Obx(() => AppBar( title: const Text("你的页面标题"), bottom: tabbarenable2.value ? BottomOfAppBar( tabs: yourTabList, controller: yourTabController, ) : null, )), )
代码优化建议
当前的 BottomOfAppBar 实现里嵌套了多余的 PreferredSize 组件,因为本身已经混入了 PreferredSizeWidget,可以直接简化:
class BottomOfAppBar extends StatelessWidget with PreferredSizeWidget { final TabBarController controller; final List<Widget> tabs; final tabbarenable2 = Get.find<RxBool>(tag: 'tabbarenable'); BottomOfAppBar({Key? key, required this.tabs, required this.controller}) : super(key: key); @override Widget build(BuildContext context) { return Obx( () => ColoredBox( color: Colors.white, child: Column( children: [ tabbarenable2.value ? TabBar( labelColor: Colors.purple[100], indicatorColor: Colors.purple, isScrollable: true, labelPadding: const EdgeInsets.only(left: 8.0), tabs: tabs) : const SizedBox.shrink(), // 不需要显示时用空白占位组件 ], ), ), ); } @override Size get preferredSize => tabbarenable2.value ? const Size.fromHeight(28.0) : Size.zero; }
内容的提问来源于stack exchange,提问作者gegentierversuche
相关产品推荐
相关产品推荐

