Flutter报错:自定义TopBar无法赋值给Scaffold的appBar参数
问题背景
需要实现响应式AppBar,要求AppBar内容变更时无需对整个Scaffold执行setState即可完成更新。
实际开发中遇到类型报错:自定义封装的BottomBar(基于BottomNavigationBar封装)可以正常赋值给Scaffold的bottomNavigationBar参数,但自定义封装的TopBar(基于AppBar封装)赋值给Scaffold的appBar参数时抛出如下错误:
The argument type 'TopBar' can't be assigned to the parameter type 'PreferredSizeWidget'
复现代码如下(仅保留State相关核心逻辑):
class StateLayoutNav extends State<LayoutNav>{ @override Widget build(BuildContext context) => Scaffold( bottomNavigationBar : BottomBar(), appBar : TopBar() ); } class StateTopBar extends State<TopBar>{ @override Widget build(BuildContext context) => AppBar(); } class StateBottomBar extends State<BottomBar>{ @override Widget build(BuildContext context) => BottomNavigationBar(); }
报错原因
- Scaffold组件的
appBar入参类型强制要求为实现了PreferredSizeWidget接口的组件,普通自定义StatefulWidget未实现该接口,无法通过类型校验 - Scaffold的
bottomNavigationBar入参只要求是普通Widget类型,无额外接口约束,因此自定义BottomBar不会触发类型报错
修复方案
让自定义的TopBar组件实现PreferredSizeWidget接口,重写preferredSize属性指定组件高度即可,AppBar默认高度对应常量为kToolbarHeight,直接复用即可。
修改后的完整核心代码:
class StateLayoutNav extends State<LayoutNav>{ @override Widget build(BuildContext context) => Scaffold( bottomNavigationBar: const BottomBar(), appBar: const TopBar() ); } // TopBar实现PreferredSizeWidget接口 class TopBar extends StatefulWidget { const TopBar({super.key}); @override State<TopBar> createState() => StateTopBar(); // 重写preferredSize属性,指定AppBar标准高度 @override Size get preferredSize => const Size.fromHeight(kToolbarHeight); } class StateTopBar extends State<TopBar>{ @override Widget build(BuildContext context) => AppBar( // 内部响应式逻辑写在这里,自身setState仅触发TopBar重建,不会影响外层Scaffold ); } class BottomBar extends StatefulWidget { const BottomBar({super.key}); @override State<BottomBar> createState() => StateBottomBar(); } class StateBottomBar extends State<BottomBar>{ @override Widget build(BuildContext context) => BottomNavigationBar(); }
补充说明
- 如果使用了自定义高度的AppBar,只需将
preferredSize中的kToolbarHeight替换为实际使用的高度值即可 - 实现接口后TopBar为独立状态组件,内部状态更新不会触发外层Scaffold重建,完全满足局部更新AppBar的需求
内容的提问来源于stack exchange,提问作者stackunderflow
相关产品推荐
相关产品推荐

