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

Flutter自定义实现PreferredSizeWidget的AppBar添加TabBar出现遮挡如何解决

问题修复方案

根本原因

自定义MySearchBar组件的preferredSize返回值固定为kToolbarHeight,未将bottom属性传入的TabBar高度计算在内。Scaffold会按照preferredSize的返回值为AppBar预留显示空间,实际AppBar渲染时需要同时容纳自身内容+TabBar,空间不足就会导致TabBar向上偏移,遮挡上层内容。

修复代码

只需要修改MySearchBar类中preferredSize的实现逻辑即可:

class MySearchBar extends StatefulWidget implements PreferredSizeWidget {
  final List<Widget> additional;
  final BuildContext? myContext;
  final PreferredSizeWidget? bottom;
  const MySearchBar({Key? key, this.bottom, this.additional = const [], this.myContext}) : super(key: key);

  // 替换原来的preferredSize实现
  @override
  Size get preferredSize {
    double baseHeight = kToolbarHeight;
    // 存在bottom组件时叠加bottom的高度
    if (bottom != null) {
      baseHeight += bottom!.preferredSize.height;
    }
    return Size.fromHeight(baseHeight);
  }

  @override
  _MySearchBarState createState() => _MySearchBarState();
}

其他代码无需修改,修改后重启应用即可看到TabBar正常显示在AppBar下方,不会再遮挡上层搜索栏区域。

效果参考

无TabBar时正常效果

无TabBar时AppBar正常效果

修复前有TabBar的异常效果

添加TabBar后AppBar被遮挡效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:36:03