Flutter中如何获取BottomNavigationBarItem的图标尺寸?
问题描述
我有一个包含BottomNavigationBarItem的列表:
final List<BottomNavigationBarItem> items = [...BottomNavigationBarItems...]
想要获取其中某个BottomNavigationBarItem的图标尺寸,尝试使用以下代码:
final iconSize = items[index].icon.size;
但报错:getter 'size' 不适用于类型 'Widget',该如何解决?
参考Flutter官方文档中BottomNavigationBarItem类的说明:其icon属性为Widget类型,并非所有Widget都具备size属性。
解决方案
因为BottomNavigationBarItem.icon是通用的Widget类型,只有当它是特定带size属性的Widget(比如Icon、ImageIcon)时,才能获取尺寸,需要先做类型判断和转换:
- 针对Icon组件的情况
if (items[index].icon is Icon) { final icon = items[index].icon as Icon; final iconSize = icon.size; // 使用iconSize }
- 针对ImageIcon组件的情况
if (items[index].icon is ImageIcon) { final imageIcon = items[index].icon as ImageIcon; final iconSize = imageIcon.size; // 使用iconSize }
- 自定义Widget的情况
如果图标是你自己封装的自定义Widget,需要在自定义Widget里暴露尺寸属性,比如:
// 自定义图标Widget class CustomNavIcon extends StatelessWidget { final double size; // ...其他属性 const CustomNavIcon({super.key, required this.size}); @override Widget build(BuildContext context) { // ...构建逻辑 } } // 获取尺寸 if (items[index].icon is CustomNavIcon) { final customIcon = items[index].icon as CustomNavIcon; final iconSize = customIcon.size; }
如果你的图标Widget是无法直接获取尺寸的类型(比如Container包裹的图标),则需要通过其他方式获取,比如在创建BottomNavigationBarItem时就把尺寸信息单独存一份到列表或对应的模型中。
内容的提问来源于stack exchange,提问作者licerer
相关产品推荐
相关产品推荐

