适配移动端与Web端的Flutter AppBar工具栏高度调整
实现Flutter AppBar自适应屏幕宽度调整高度
你可以通过MediaQuery获取屏幕宽度,动态设置AppBar的高度,实现Web宽屏(>1100px)和移动端的差异化布局,以下是两种实用方案:
方案一:基于默认AppBar快速实现
直接利用AppBar的toolbarHeight属性,根据屏幕宽度动态赋值:
@override Widget build(BuildContext context) { // 获取当前屏幕宽度 final screenWidth = MediaQuery.of(context).size.width; // 定义不同场景下的AppBar高度 final appBarHeight = screenWidth > 1100 ? 80.0 : 56.0; return Scaffold( appBar: AppBar( toolbarHeight: appBarHeight, title: const Text('自适应高度工具栏'), // 其他AppBar配置(如actions、leading等) ), body: const Center(child: Text('页面内容')), ); }
方案二:自定义AppBar(适合复杂布局场景)
如果需要在宽屏时添加更多元素(如搜索框、菜单按钮),可以用PreferredSize自定义AppBar:
@override Widget build(BuildContext context) { final screenWidth = MediaQuery.of(context).size.width; final appBarHeight = screenWidth > 1100 ? 80.0 : 56.0; return Scaffold( appBar: PreferredSize( preferredSize: Size.fromHeight(appBarHeight), child: Container( height: appBarHeight, color: Theme.of(context).primaryColor, padding: const EdgeInsets.symmetric(horizontal: 16), child: Row( children: [ const Text('自定义自适应工具栏'), // 宽屏时额外显示搜索框和设置按钮 if (screenWidth > 1100) ...[ const SizedBox(width: 20), const Expanded( child: TextField( decoration: InputDecoration( hintText: '搜索内容', filled: true, fillColor: Colors.white24, ), ), ), IconButton( icon: const Icon(Icons.settings), onPressed: () {}, ), ], ], ), ), ), body: const Center(child: Text('页面内容')), ); }
关键注意事项
- 无需额外监听窗口变化:Flutter会在屏幕尺寸改变时自动重建Widget,高度会实时更新
- 高度数值可根据需求调整:示例中80px适合Web宽屏,56px是Flutter默认AppBar高度,适配移动端
- 确保在
build方法内使用MediaQuery:只有在有Context的场景下才能正确获取屏幕尺寸
内容的提问来源于stack exchange,提问作者Sheldon Osotsi
相关产品推荐
相关产品推荐

