如何在保持图标高度不变时缩减BottomNavigationBar上下内边距并设栏高为50px
我来帮你搞定这个溢出问题,先分析下根源,再给你具体的修复方案:
问题出在哪?
你遇到的4像素溢出,主要是两个原因叠加导致的:
BottomNavigationBarItem里的空Text('')并没有完全不占空间,它会保留默认的文本行高,偷偷占用了一部分高度BottomNavigationBar本身自带默认的上下内边距,加上图标高度和空文本的额外高度,总和超过了你设置的50像素容器高度
修复步骤&代码
按照下面的修改调整,就能实现你要的效果:
移除空文本的无效占位
把BottomNavigationBarItem里的title: Text('')改成title: null(如果是Flutter 2.0+版本,也可以直接省略title参数,改用label: null),彻底消除空文本的高度占用。自定义导航栏的内边距
给BottomNavigationBar添加padding属性,手动缩减上下内边距,确保图标高度(24px)加上上下内边距的总和不超过50px。补上方法的返回语句
你的buildBottomBarItems方法原来漏掉了返回列表的语句,这会导致编译错误,我已经在代码里补上了。
修改后的完整代码
bottomNavigationBar: SizedBox( height: 50, child: BottomNavigationBar( showSelectedLabels: false, showUnselectedLabels: false, type: BottomNavigationBarType.fixed, elevation: 5.0, currentIndex: 0, // 自定义上下内边距,可根据实际显示微调数值 padding: const EdgeInsets.symmetric(vertical: 3), items: buildBottomBarItems(), ), )
List<BottomNavigationBarItem> buildBottomBarItems() { List<BottomNavigationBarItem> _bottomBarItems = []; List<String> _iconNames = ["home", "search", "plus", "heart"]; for (var i = 0; i < _iconNames.length; ++i) { _bottomBarItems.add( BottomNavigationBarItem( icon: Container( child: Image.asset('assets/${_iconNames[i]}.png', width: 24, height: 24), ), // 替换空文本为null,消除多余高度 title: null, ), ); } // 补上返回语句,否则无法生成导航栏项 return _bottomBarItems; }
额外小提示
如果调整内边距后还是有溢出,可以试试:
- 稍微减小内边距的
vertical值(比如设为2) - 给
Image.asset加上fit: BoxFit.contain,确保图标完全填充24x24的容器,避免图标自带透明边距占用额外空间
内容的提问来源于stack exchange,提问作者Florian K
相关产品推荐
相关产品推荐

