Flutter中带默认安全区的iPhone底部导航栏项如何居中对齐?
问题根因
你遇到的对齐问题是两个核心原因导致的:
- 外层自定义的底部导航容器定死了高度,但没有适配iPhone底部安全区的额外padding,
BottomNavigationBar默认会自动叠加安全区边距,在定高容器内就会出现内容被挤压偏移的情况 - 你隐藏了
BottomNavigationBar的系统标签,但组件默认仍为标签预留了底部内边距,导致图标整体上移无法居中
修复方案
按以下步骤调整代码即可:
- 调整外层容器的高度计算,额外叠加底部安全区高度,同时移除不必要的
Align包裹 - 给
BottomNavigationBar添加属性清除标签预留的内边距,同时关闭多余的默认边距 - 确认自定义的
BottmNavTabButton组件本身内容是居中布局的
修改后的代码示例
Scaffold( body: _children[watch(tabviewProvider).currentBottomNavIndex], // 直接用SafeArea包底部导航更方便适配安全区 bottomNavigationBar: SafeArea( child: Visibility( visible: !watch(tabviewProvider).isBottomTabbarHide, child: Container( height: SizeConfig.blockSizeVertical * 10, decoration: BoxDecoration( color: Colors.orange,//Todo:remove boxShadow: <BoxShadow>[ BoxShadow( color: Color(0xffE5E5E5), blurRadius: 5, ), ], ), child: BottomNavigationBar( backgroundColor: Colors.grey, //Todo:remove // backgroundColor: Color(0xffF7F3ED), selectedFontSize: 0, showSelectedLabels: false, showUnselectedLabels: false, type: BottomNavigationBarType.fixed, // 清除标签预留的内边距 selectedLabelStyle: TextStyle(height: 0), unselectedLabelStyle: TextStyle(height: 0), // 清除默认多余边距 padding: EdgeInsets.symmetric(vertical: 0), key: bottomNavGlobalKey, onTap: onTabTapped, currentIndex: watch(tabviewProvider).currentBottomNavIndex, items: [ BottomNavigationBarItem( activeIcon: BottmNavTabButton( isActive: true, imgPath: 'assets/icons/icon_timeline_pink.svg', lableText: 'A', ), label: '', icon: BottmNavTabButton( isActive: false, imgPath: 'assets/icons/icon_timeline_gray.svg', lableText: 'A', ), ), BottomNavigationBarItem( activeIcon: BottmNavTabButton( isActive: true, imgPath: 'assets/icons/icon_knowledge_pink.svg', lableText: 'B', ), label: '', icon: BottmNavTabButton( isActive: false, imgPath: 'assets/icons/icon_knowledge_gray.svg', lableText: 'B', ), ), BottomNavigationBarItem( activeIcon: BottmNavTabButton( isActive: true, imgPath: 'assets/icons/icon_offer_pink.svg', lableText: 'C', ), label: '', icon: BottmNavTabButton( isActive: false, imgPath: 'assets/icons/icon_offer_gray.svg', lableText: 'C', ), ) ], ), ), ), ), );
额外验证点
如果调整后仍有偏移,可以检查自定义BottmNavTabButton的布局,确认其内部没有设置额外的顶部/底部padding,自身是主轴交叉轴双居中布局。
内容的提问来源于stack exchange,提问作者Shashiwadana
相关产品推荐
相关产品推荐

