как добавить значение API в список? - PullRequest
0 голосов
/ 06 августа 2020

это ответ 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 "
    },
]
  1. Я хотел добавить «имя_строения» в список
  2. Одно и то же имя не должно повторяться

Я пробовал этот способ, но не работал

static List<Map<String, String>> choices = <Map<String, String>>[
    {
        "title": building_name, "id": building_name
    },
];

я вызываю значение типа

child: Text(choice["title"],),

1 Ответ

0 голосов
/ 06 августа 2020

Вот как я бы это сделал:

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}]
...