问题描述
这是我在 Dart 中使用的 Map 数据结构的当前状态:
Map database = {
'campusConnect': {
'hashtags': [
{
'id': 4908504398,'title': '#NeverGiveUp!','author': 'ABC',},{
'id': 430805,'title': '#ItAlwaysTakesTime','author': 'XYZ'
}
]
}
};
我想查看主题标签数组。遍历该数组中的每个对象,我想将“id”字段与我已有的某个数字进行比较。我该怎么做?
到目前为止,这是我尝试做的:
database['campusConnect']['hashtags'].map( (item) {
print('I am here ...');
if (item['id'] == hashtagId) {
print(item['title']);
}
});
我不知道为什么,但它没有给我任何错误并且不能同时工作。当我运行它时,它甚至不打印“我在这里......”。
注意 if 块中的标识符“hashtagId”:
if (item['id'] == hashtagId) { ... }
这是在函数中作为参数传递的。为简单起见,我没有展示函数,但假设这是我收到的 int 类型参数
我应该如何做到这一点?
解决方法
以下方法将解决您的问题。
void test(){
final hashTags = database['campusConnect']['hashTags'];
if(hashTags is List){
for(var i=0; i<hashTags.length; i++){
final id = hashTags[i]['id'];
if(id == hashtagId){
// do something
}
}
}
}
,
Flutter 足够聪明,可以跳过什么都不做的代码。在您的情况下,您没有使用 map()
函数的结果。尝试使用 forEach()
更改它并修复 hashTags
错字
database['campusConnect']['hashTags'].forEach((item) {
print('I am here ...');
if (item['id'] == hashtagId) {
print(item['title']);
}
});