Flutter使用SVG作为PersistentNavBarItem图标,颜色不生效问题求助
直接传入SvgPicture.asset实例时,PersistentBottomNavBarItem的activeColorPrimary和inactiveColorPrimary无法控制SVG颜色,原因是SVG自身的fill属性会覆盖组件的颜色设置,或者组件无法直接修改已初始化的SvgPicture的颜色属性。以下是两种可行的解决方法:
方法一:修改SVG文件+指定activeIcon/Icon
修改SVG文件
打开你的SVG文件,将所有固定的fill属性值替换为currentColor,例如把fill="#123456"改成fill="currentColor",让SVG继承父组件的颜色值。更新代码
通过icon和activeIcon分别指定非激活态和激活态的SVG,并设置对应颜色:
List<PersistentBottomNavBarItem> _navbarItems = [ PersistentBottomNavBarItem( icon: SvgPicture.asset( 'images/sofa_home.svg', width: 22, color: ColorsConst.blueThree, ), activeIcon: SvgPicture.asset( 'images/sofa_home.svg', width: 22, color: ColorsConst.yellow, ), activeColorPrimary: ColorsConst.yellow, inactiveColorPrimary: ColorsConst.blueThree, title: 'Home', ), PersistentBottomNavBarItem( icon: SvgPicture.asset( 'images/sofa_search.svg', width: 22, color: ColorsConst.blueThree, ), activeIcon: SvgPicture.asset( 'images/sofa_search.svg', width: 22, color: ColorsConst.yellow, ), activeColorPrimary: ColorsConst.yellow, inactiveColorPrimary: ColorsConst.blueThree, title: 'Browse', ), PersistentBottomNavBarItem( icon: SvgPicture.asset( 'images/sofa_profile.svg', width: 22, color: ColorsConst.blueThree, ), activeIcon: SvgPicture.asset( 'images/sofa_profile.svg', width: 22, color: ColorsConst.yellow, ), activeColorPrimary: ColorsConst.yellow, inactiveColorPrimary: ColorsConst.blueThree, title: 'Account', ), ];
为减少重复代码,可封装工具方法:
Widget _buildThemedSvg(String assetPath, Color color) { return SvgPicture.asset( assetPath, width: 22, color: color, ); } // 调用示例 PersistentBottomNavBarItem( icon: _buildThemedSvg('images/sofa_home.svg', ColorsConst.blueThree), activeIcon: _buildThemedSvg('images/sofa_home.svg', ColorsConst.yellow), // 其他属性不变 )
方法二:使用ColorFiltered滤镜(无需修改SVG)
如果无法修改SVG文件,可通过ColorFiltered组件给SVG添加颜色滤镜,强制覆盖原有颜色:
Widget _buildThemedSvg(String assetPath, Color color) { return ColorFiltered( colorFilter: ColorFilter.mode(color, BlendMode.srcIn), child: SvgPicture.asset( assetPath, width: 22, ), ); } // 后续代码调用方式与方法一一致
这种方法通过颜色混合模式将指定颜色应用到SVG上,无需改动SVG文件内容。
内容的提问来源于stack exchange,提问作者Sofiane KARAOUNI
相关产品推荐
相关产品推荐

