如何解决Flutter 基于 Map 显示 iconButton
我有一张这样的地图:
static const Map<String,Map<String,String>> social = {
'personA': {
'twitch': 'https://www.twitch.tv/...','instagram': 'https://www.instagram.com/.../'
},'personB': {
'twitch': 'https://www.twitch.tv/...','personC': {
'facebook': 'https://www.facebook.com/...',},};
可以为每个图标显示带有 font_awesome 图标的 iconButton 社交与每个人相关,点击重定向到链接?,如何?
我是这样试的:
Row(
children: <Widget>[
ListView.builder(
itemBuilder: (_) {
return Constants.social[person].keys.map((e) =>
IconButton(icon: FaIcon(FontAwesomeIcons.e),onpressed: {
print("example");
});
);
}
)
],),
但我收到错误:
The argument type 'Widget Function(BuildContext)' can't be assigned to the parameter type 'Widget Function(BuildContext,int)'
变量 person 可以包含 personA、personB 或 personC。
例如,对于personA,我想显示2个iconButton,一个用于twitch,一个用于instagram,但对于personC,我只想显示facebook图标。
解决方法
ListView 是一个代表 a list of widgets arranged linearly 的小部件。
您有多个用于此小部件的构造函数。您使用的 ListView.builder()
是当要显示大量子项时建议使用的一种。 (在您的示例中,如果地图包含许多玩家。)
默认构造函数只需要一个 List<Widget>
并且要简单得多。如果您没有大地图,我强烈建议您改用此地图。但既然您尝试使用 builder
之一,您应该执行以下操作:
- 首先,将您的数据排列在一个列表中。通过这种方式,您可以轻松地通过整数索引访问元素:
List[0]
。理想情况下,您应该已经拥有列表形式的数据,但如果您需要,您可以像这样转换它:
static const Map<String,Map<String,String>> social = {
'personA': {
'twitch': 'https://www.twitch.tv/...','instagram': 'https://www.instagram.com/.../'
},'personB': {
'twitch': 'https://www.twitch.tv/...','personC': {
'facebook': 'https://www.facebook.com/...',},};
List<Map<String,String>> listUsers = List().from(social.values);
- 通过 itemCount 参数提供列表视图将具有的条目数:
[...]
ListView.builder(
itemCount: listUsers.length,itemBuilder: (context,index) {
[...]
- 您的错误表明构建器函数需要接收另一个整数参数:
'Widget Function(BuildContext)'不能分配给参数类型
'小部件函数(BuildContext,int)```.
这个整数参数表示它将是列表中的哪个小部件。您的构建器函数只需要返回一个小部件,并且它接收索引参数以便您知道它是哪一个:
Row(
children: <Widget>[
ListView.builder(
itemCount: listUsers.length,index) {
return Column(children:[
if (listUsers[index].containsKey('twitch'))
IconButton(icon: FaIcon(FontAwesomeIcons.twitch),onPressed: (){//Access listUsers[index]['twitch'] here
}),if (listUsers[index].containsKey('instagram'))
IconButton(icon: FaIcon(FontAwesomeIcons.instagram),onPressed: (){//Access listUsers[index]['instagram'] here
})
])
}
)
],),
这应该足以获得您想要的结果。作为建议,您可以阅读 official documentation,其中有许多很好的示例和解释。 Dart Language tour 也是有关语言示例的好地方。它们都写得很好,在这种情况下会让你走上正轨。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。