【问题标题】:how to add API value to a list?如何将 API 值添加到列表中?
【发布时间】:2020-08-06 09:03:33
【问题描述】:

这是 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. 我想将“building_name”添加到列表中
  2. 同名不能重复

我试过这种方法,但不起作用

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

我正在调用这个值

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

【问题讨论】:

    标签: android ios flutter dart flutter-layout


    【解决方案1】:

    我会这样做:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多