使用PreferredSize组件时AppBar无法设置title,求替代方案?
正确使用PreferredSize组件的方法
问题原因
你遇到的两个错误本质是:
PreferredSize组件本身没有title这个命名参数,它仅接受preferredSize和child两个必填参数- 原代码存在语法错误:
appBar: PreferredSize(title: Text('hi');多了分号,且参数传递格式混乱
正确写法示例
方式1:纯自定义容器作为AppBar
要在自定义高度的AppBar里添加标题,直接把标题嵌套到child参数的容器中即可:
@override Widget build(BuildContext context) { double _w = MediaQuery.of(context).size.width; return Scaffold( appBar: PreferredSize( preferredSize: const Size.fromHeight(100), // 自定义AppBar高度 child: Container( color: Colors.blueGrey, alignment: Alignment.center, // 控制标题居中 child: const Text( 'hi', style: TextStyle(fontSize: 20, color: Colors.white), ), ), ), body: const Center(child: Text('页面内容')), ); }
方式2:保留原生AppBar功能
如果需要保留AppBar的原生特性(比如返回按钮、右侧操作按钮等),可以把AppBar作为PreferredSize的child:
@override Widget build(BuildContext context) { double _w = MediaQuery.of(context).size.width; return Scaffold( appBar: PreferredSize( preferredSize: const Size.fromHeight(100), child: AppBar( title: const Text('hi'), backgroundColor: Colors.blueGrey, centerTitle: true, // 可添加原生AppBar的其他属性 actions: [ IconButton(onPressed: () {}, icon: const Icon(Icons.settings)), ], ), ), body: const Center(child: Text('页面内容')), ); }
替代方案
如果只是需要自定义高度的AppBar,无需嵌套PreferredSize,直接给原生AppBar设置toolbarHeight属性即可:
@override Widget build(BuildContext context) { double _w = MediaQuery.of(context).size.width; return Scaffold( appBar: AppBar( title: const Text('hi'), backgroundColor: Colors.blueGrey, toolbarHeight: 100, // 直接指定高度 centerTitle: true, ), body: const Center(child: Text('页面内容')), ); }
内容的提问来源于stack exchange,提问作者fluttergogo
相关产品推荐
相关产品推荐

