You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

适配移动端与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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 17:55:18