flutter - 将地图项读入类成员
问题描述
我将以下 JSON 数据加载到我的 Flutter 应用程序中:
{
"Games": [
{
"name": "Sample Name",
"categories": [
{
"name": "Category 1",
"multiplier": 1,
"order": 2
},
{
"name": "Category 2",
"order": 9,
"Range": [
{
"ceiling": 0,
"floor": 0,
"score": 0
},
{
"ceiling": 1,
"floor": 1,
"score": 2
}
]
},
{
"name": "Category 4",
"multiplier": -1,
"order": 11,
"penalty": true
},
{
"name": "Category 5",
"multiplier": 1,
"order": 8
},
{
"name": "Category 6",
"multiplier": -1,
"order": 10,
"penalty": true
}
],
"enabled": true,
"maxPlayers": 4,
"minPlayers": 1
}
]
}
我正在使用以下代码从上述地图中填充对象:
class Entry {
String name;
// final String filename;
int minPlayers;
int maxPlayers;
bool enabled;
bool selected = false;
DocumentReference reference;
List<Category> categories;
Entry.fromMap(Map<String, dynamic> map, {this.reference}) {
name = map['name'];
enabled = map['enabled'];
minPlayers = map['minPlayers'];
maxPlayers = map['maxPlayers'];
categories =
(map['categories'].map((data) => Category.fromMap(data)).toList());
}
class Category {
String name;
int order;
int multiplier;
bool penalty;
Category.fromMap(Map<String, dynamic> map, {DocumentReference reference}) {
name = map['name'];
order = map['order'];
multiplier = map['multiplier'];
penalty = !map.containsKey('penalty');
}
Category.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
}
当我运行它时,我收到以下错误:
type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>'
如何将类别元素的集合放入可迭代的对象列表中以保存每个类别,并从 map['categories'] 中的单个元素加载它?
解决方案
我认为您尚未为各自的 json 创建有效的 dart 类。您的 json 具有像 Entry 类这样的架构,其中包含多个游戏,
每个游戏都有多个类别,
每个类别都有多个 Range。
请使用此工具将您的 json 转换为 Dart 类
我已经为您的 json 创建了模型类,请检查此链接。
现在是解析的时候了。我只是将欢迎类重命名为条目。
解析
final jsonResponse = json.decode('YOUR JSON STRING');
Entry entry =Entry.fromJson(jsonResponse);
print(entry.games.length);
entry.games.map((game) {
print("Game Name " + game.name + "----------");
print("Category List");
game.categories.map((category) {
print(category.name);
}).toList();
}).toList();
现在检查调试控制台。所有类别和游戏显示。
推荐阅读
- java - 未调用 Spring Boot Servlet 过滤器
- c++ - 如何公开匿名工会的单个成员?
- ruby-on-rails - 尽管控制台显示参数正确传递并且控制器正确调用,Rails 参数传递问题
- javascript - 在Angular中将参数传递给css类
- python - 销售税和账单(第 2 部分)(python3)
- git - git log 包含另一个分支的提交,如何在分支之间分离提交
- r - 使用 R 中的 gt 包更改存根行组中的缩进
- rest - Google Drive API Resumable Upload PUT 请求失败。状态码:400。消息:未找到
- css - 纵向查看时,英雄图像不是全高
- android - 设置中的字体大小使 TextView 中的文本不可读且重叠