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

Flutter中如何修改CupertinoNavigationBar的高度?

问题原因

出现双导航栏的核心原因有两个:

  • 你在使用CupertinoPageScaffold或CupertinoApp时,同时配置了系统自带的navigationBar参数,又在页面body中嵌套了自定义的CustomCupertinoNavigationBar,两个导航栏同时渲染叠加
  • 即使没有同时配置两个导航栏,Flutter默认的iOS页面适配逻辑会自动给页面顶部添加系统默认导航栏高度的安全区padding,你修改自定义导航栏高度后,安全区高度和自定义导航栏高度不匹配,会出现多余空白或叠层效果,视觉上类似两个导航栏
解决方案

无需拷贝修改Flutter源码,更稳定的修改方式如下:

方案1:强制指定导航栏高度+关闭默认导航栏

你可以直接在外层包裹SizedBox指定导航栏高度,同时关闭脚手架自带的导航栏插入逻辑,示例代码如下:

CupertinoPageScaffold(
  // 关闭系统自动插入导航栏,避免重复渲染
  navigationBar: null,
  body: Column(
    children: [
      // 外层套SizedBox指定你需要的导航栏高度
      SizedBox(
        height: 58,
        child: CustomCupertinoNavigationBar(
          padding: EdgeInsetsDirectional.zero,
          backgroundColor: Colors.white,
          middle: Semantics(
            label: "dashboard-main-page-title",
            child: Text(
              "My Title",
              style: TextStyles.HankenSans_Bold_18_PrimaryBlack,
              key: Key('dashboard-main-page-title'),
            ),
          ),
          leading: Semantics(
            label: "dashboard-back-button",
            child: Material(
              color: Colors.white,
              child: CustomBackButton(
                onPressHandler: () {
                  Navigation().openMyAccountPage();
                },
              ),
            ),
          ),
        ),
      ),
      // 页面主体内容
      Expanded(
        child: SafeArea(
          // 顶部安全区已经由导航栏处理,关闭避免出现多余空白
          top: false,
          child: // 你的页面业务内容
        ),
      )
    ],
  ),
)

方案2:重写preferredSize自定义导航栏高度

CupertinoNavigationBar本身实现了PreferredSizeWidget协议,你可以直接继承重写高度参数,适配脚手架的导航栏配置逻辑:

class CustomHeightCupertinoNavigationBar extends CupertinoNavigationBar {
  final double customHeight;
  
  const CustomHeightCupertinoNavigationBar({
    super.key,
    required this.customHeight,
    super.middle,
    super.leading,
    super.backgroundColor,
    super.padding,
    // 其他你需要透传的参数
  });

  @override
  Size get preferredSize => Size.fromHeight(customHeight);
}

使用时直接将该自定义组件传给CupertinoPageScaffold的navigationBar参数即可,无需额外处理布局,也不会出现双导航栏问题。

原有改源码方案的修复方式

如果你要继续使用之前修改源码生成的CustomCupertinoNavigationBar,只需要检查两个配置:

  • 确保没有同时给页面脚手架配置其他navigationBar参数
  • 确保自定义导航栏的内部元素布局已经适配你修改后的58高度,不会出现溢出、偏移问题

内容的提问来源于stack exchange,提问作者desdemona

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:18:04