Flutter中如何通过方括号动态访问对象的键属性
Dart/Flutter 动态键访问对象属性问题
问题复现
我在DartPad中运行如下Dart代码时可以正常执行:
import 'package:intl/intl.dart'; void main() { final matches = [ { "match_id": 6604501658, "player_slot": 129, "radiant_win": false, "duration": 2020, "game_mode": 22, "lobby_type": 7, "hero_id": 19, "start_time": 1654520510, "version": 21, "kills": 13, "deaths": 7, "assists": 17, "skill": null, "xp_per_min": 780, "gold_per_min": 604, "hero_damage": 36271, "tower_damage": 10042, "hero_healing": 0, "last_hits": 211, "lane": 2, "lane_role": 2, "is_roaming": false, "cluster": 156, "leaver_status": 0, "party_size": 1 }, { "match_id": 6604451816, "player_slot": 4, "radiant_win": false, "duration": 1242, "game_mode": 22, "lobby_type": 7, "hero_id": 52, "start_time": 1654518740, "version": 21, "kills": 7, "deaths": 4, "assists": 1, "skill": null, "xp_per_min": 540, "gold_per_min": 472, "hero_damage": 14678, "tower_damage": 2111, "hero_healing": 0, "last_hits": 136, "lane": 2, "lane_role": 2, "is_roaming": false, "cluster": 156, "leaver_status": 0, "party_size": 1 } ]; final List<String> extraList = ['kills','deaths','assists','gold_per_min','xp_per_min','last_hits','hero_damage','hero_healing','tower_damage','duration']; for(var i in extraList) { print(averMax(matches, i)); } } String averMax(dynamic matches, String field) { final dynamic matchesMap = matches.map((match) => match[field]); final dynamic matchesReduce = matchesMap.reduce((cur, total) => cur + total); return field != 'duration' ? greaterNum((matchesReduce / 20).round(), 1000, 'K') : (matchesReduce / 20).toString(); } String greaterNum(double num, int gN, String unit) { var minus = ''; if (num < 0) { minus = '-'; } num = (num).abs(); if (num > gN) { final newNum = (num / gN).toStringAsFixed(1); return '$minus$newNum$unit'; } else { return '$minus$num'; } }
上述代码在DartPad中运行无异常,但放到Flutter项目中时出现问题:项目里从API获取的PlayerMatches是强类型模型对象组成的List,我需要将extraList中的字符串作为键,动态读取matches列表的对应字段值,传递给ListView组件渲染。
在DartPad中直接用match[field]的方括号写法可以正常取值,但在Flutter项目中用相同写法访问强类型对象的属性会直接报错。
注:DartPad中测试代码的matches本身是List<Map>结构,[]是Map类型原生支持的键访问方式,和Flutter项目中的强类型模型对象本质不是同一种数据结构。
疑问
Dart/Flutter是否支持类似JavaScript的动态键访问对象属性的写法?
解决方案
Dart的强类型自定义类实例不支持直接通过方括号传入字符串键的方式访问属性,只要先调用模型类的toJson()方法,把强类型对象转为Map结构,就可以继续用方括号+动态键的方式取值了,示例代码如下:
return match.toJson()[field];
内容的提问来源于stack exchange,提问作者iversonLv
相关产品推荐
相关产品推荐

