android - 如何将 API 值添加到列表中?
问题描述
这是 API 响应
[
{
"building_name": "Burj Khalifa",
"unit_number": "101",
"unit_type": "flat",
"sub_type": "1bhk",
"unit_space": "500",
"annual_rent": "25000",
"annual_rent_in_word": "twenty five thousand "
},
{
"building_name": "Burj Khalifa",
"unit_number": "102",
"unit_type": "flat",
"sub_type": "2bhk",
"unit_space": "900",
"annual_rent": "25000",
"annual_rent_in_word": "twenty five thousand "
},
{
"building_name": "alzimar",
"unit_number": "103",
"unit_type": "flat",
"sub_type": "1bhk",
"unit_space": "500",
"annual_rent": "25000",
"annual_rent_in_word": "twenty five thousand "
},
]
- 我想将“building_name”添加到列表中
- 同名不能重复
我试过这种方式但没有工作
static List<Map<String, String>> choices = <Map<String, String>>[
{
"title": building_name, "id": building_name
},
];
我正在调用这个值
child: Text(choice["title"],),
解决方案
这是我的做法:
List apiResponseList = [
{
"building_name": "Burj Khalifa",
"unit_number": "101",
"unit_type": "flat",
"sub_type": "1bhk",
"unit_space": "500",
"annual_rent": "25000",
"annual_rent_in_word": "twenty five thousand "
},
{
"building_name": "Burj Khalifa",
"unit_number": "102",
"unit_type": "flat",
"sub_type": "2bhk",
"unit_space": "900",
"annual_rent": "25000",
"annual_rent_in_word": "twenty five thousand "
},
{
"building_name": "alzimar",
"unit_number": "103",
"unit_type": "flat",
"sub_type": "1bhk",
"unit_space": "500",
"annual_rent": "25000",
"annual_rent_in_word": "twenty five thousand "
},
];
然后映射apiResponseList
到新列表中:
List<Map<String, String>> choices = [];
for (var item in apiResponseList) {
if (choices.isEmpty) {
choices
.add({"title": item['building_name'], "id": item['building_name']});
} else {
//This adds the map only if `choices` does not contain the same `building name`
if (choices.any((test) => test['title'] != item['building_name'])) {
choices
.add({"title": item['building_name'], "id": item['building_name']});
}
}
}
如果你跑print(choices)
,你会得到
[{title: Burj Khalifa, id: Burj Khalifa}, {title: alzimar, id: alzimar}]
推荐阅读
- c# - 如何在 TextChange 事件中更改 MaskedTextBox 的文本颜色?
- android - 无法连接到流星 android-device 上的托管或本地 mongo
- javascript - 为什么我的函数会过滤掉零和字符串?
- git - 用于通用远程存储库的 MacOS SourceTree 清除凭证助手
- python - 类变量不与类实例共享
- python - 寻求有关python项目的帮助
- python - Pythong PuLP 约束:如何构建递归约束
- php - 网站上 CSS 搜索结果的问题
- python - 使用 Python Selenium 登录到具有 JS 生成的登录表单的网站
- java - 如何下载excel并在单击jsp上的链接时从spring控制器返回一些错误消息