Flutter:根据值显示不同的图标 [英] Flutter: Show different icons based on value
问题描述
我有一个带有图标属性的对象列表,如下所示:
I have a list of objects each with an icon property as shown here:
List<Map<String, String>> _categories = [
{
'name': 'Sports',
'icon': 'directions_run',
},
{
'name': 'Politics',
'icon': 'gavel',
},
{
'name': 'Science',
'icon': 'wb_sunny',
},
];
然后我在ListView.builder()小部件中有一个小部件正在使用。目前,我正在显示一个静态选择的图标,以与列表中的文本一起显示。我的问题是如何使用对象中的icon属性动态地选择为每个单独的列表项显示的图标?
I then have a widget that I am using inside of a ListView.builder() widget. Currently I am displaying a statically chosen icon to show with the text in my list. My question is how can I use the icon property in my objects to dynamically pick the icon that gets shown for each individual list item?
Widget _buildCategoryCards(BuildContext context, int index) {
return Container(
padding: EdgeInsets.symmetric(vertical: 5.0),
child: Card(
child: Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Icon(Icons.directions_run),
SizedBox(width: 20.0),
Text(_categories[index]['name']),
],
),
),
),
);
}
推荐答案
更改您的列出
来存储 IconData
而不是 String
:
Change your List
to store an IconData
instead of a String
:
List<Map<String, IconData>> _categories = [
{
'name': 'Sports',
'icon': Icons.directions_run,
},
{
'name': 'Politics',
'icon': Icons.gavel,
},
{
'name': 'Science',
'icon': Icons.wb_sunny,
},
];
然后,从构建中调用 IconData
方法:
Then, call the IconData
from your build method:
Widget _buildCategoryCards(BuildContext context, int index) {
return Container(
padding: EdgeInsets.symmetric(vertical: 5.0),
child: Card(
child: Container(
padding: EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Icon(_categories[index]['icon']),
SizedBox(width: 20.0),
Text(_categories[index]['name']),
],
),
),
),
);
}
请注意,这不是使用地图
进行所需的操作非常有用(甚至没有效率)。您应该使用自定义类:
Note that this is not useful (even not effecient) to use a Map
to do what you want. You should use a custom class:
Class Category {
String name;
IconData icon;
Category(this.name, this.icon);
}
然后替换您的列表
:
List<Category> _categories = [
Category('Sports', Icons.directions_run),
Category('Politics', Icons.gavel),
Category('Science', Icons.wb_sunny),
];
最后在您的小部件中:
children: <Widget>[
Icon(_categories[index].icon),
SizedBox(width: 20.0),
Text(_categories[index].name),
],
这篇关于Flutter:根据值显示不同的图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!