Flutter中如何增大BottomNavigationBar选中状态的图标尺寸
问题原因
你当前配置的selectedIconTheme、unselectedIconTheme属性仅对原生Icon组件生效,你的底部导航项使用Image.asset加载自定义图片作为图标,且硬编码了固定的height:25、width:25,所以全局的图标主题配置无法作用到自定义图片上。
注意:请先删除原有代码末尾注释的重复
selectedIconTheme、unselectedIconTheme配置,避免出现属性覆盖问题。
解决方案
方案1:直接根据选中状态动态设置图片尺寸
最简单的实现方式,直接在每个Image.asset的宽高属性中,根据当前选中的index判断对应尺寸即可,示例修改代码如下:
BottomNavigationBar( selectedIconTheme: const IconThemeData(size: 30), unselectedIconTheme: const IconThemeData(size: 24), items: [ BottomNavigationBarItem( icon: Image.asset( index == 0 ? "assets/homeScreenImages/appointment_active.png" : "assets/homeScreenImages/appointment_unactive.png", // 动态设置宽高 height: index == 0 ? 30 : 24, width: index == 0 ? 30 : 24, fit: BoxFit.cover, ), label: APPOINTMENT, ), BottomNavigationBarItem( icon: Image.asset( index == 1 ? "assets/homeScreenImages/home_active.png" : "assets/homeScreenImages/home_unactive.png", height: index == 1 ? 30 : 24, width: index == 1 ? 30 : 24, fit: BoxFit.cover, ), label: HOME, ), BottomNavigationBarItem( icon: Image.asset( index == 2 ? "assets/homeScreenImages/more_active.png" : "assets/homeScreenImages/more_unactive.png", height: index == 2 ? 30 : 24, width: index == 2 ? 30 : 24, fit: BoxFit.cover, ), label: MORE, ), ], // 其余原有配置保持不变 selectedLabelStyle: GoogleFonts.poppins( color: Colors.black, fontSize: 8, ), type: BottomNavigationBarType.fixed, unselectedLabelStyle: GoogleFonts.poppins( color: Colors.black, fontSize: 7, ), unselectedItemColor: Colors.grey.shade500, selectedItemColor: Colors.black, onTap: (i) { setState(() { index = i; }); }, currentIndex: index, )
如果需要大小切换有平滑过渡效果,可以把Image.asset包在AnimatedContainer里,设置duration参数即可。
方案2:复用IconTheme配置
如果你后续需要统一调整尺寸,不想逐个修改每个图片的宽高判断,可以直接读取当前上下文的IconTheme尺寸,这样你在BottomNavigationBar上配置的selectedIconTheme、unselectedIconTheme的size值就会自动生效:
Image.asset( // 你的图片路径逻辑不变 index == 0 ? "xxx_active.png" : "xxx_unactive.png", // 直接读取当前主题的图标尺寸 height: IconTheme.of(context).size, width: IconTheme.of(context).size, fit: BoxFit.cover, )
内容的提问来源于stack exchange,提问作者Avdhesh Purohit
相关产品推荐
相关产品推荐

