как получить соответствующее значение списка <string>из api во флаттере? - PullRequest
0 голосов
/ 05 августа 2020

это мой ответ API

var = ''' [
{
    "entity_id": "86",
    "building_name": "Burj Khalifa",
    "location": "Al  Ttay",
    "image_field": "1595916594oad.jpeg"
},
{
    "entity_id": "87",
    "building_name": "Azmair",
    "location": " Eyal Nasser ",
    "image_field": "1596541099s.jpeg"
},
  {
    "entity_id": "88",
    "building_name": "Bella Casa",
    "location": "Hatta",
    "image_field": "15965463423abe68a5bc11733effefeb91194_767x0.jpg"
  }
]''';

Я делаю это как строку, используя

var decoded = response as List;
var buildgnames = decoded.map<String>((e) => e['building_name']).toList();

как получить «entity_id» с помощью при выборе имени здания в списке?

например, когда я выбираю "Burj Khalifa" в раскрывающемся списке, я хочу получить его "id"

Ответы [ 4 ]

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

Прежде всего вам нужно создать класс модели.

 class Building {
  String id;
  String buildingName;
  String location;
  String imageField;

  Building({this.id, this.buildingName, this.location, this.imageField});

  Building.fromJson(Map<String, dynamic> json) {
    id = json['entity_id'];
    buildingName = json['building_name'];
    location = json['location'];
    imageField = json['image_field'];
  }
}

После этого преобразовать ответ в объект Building.

 Iterable mJson = json.decode(response.body);
 List<Building> buildingList = mJson.map((model) => Building.fromJson(model)).toList();

Показать имя списка зданий и вернуть идентификатор здания при нажатии.

Expanded(
        child: ListView.separated(
            separatorBuilder: (context, index) => Divider(
                  color: Colors.grey,
                ),
            itemCount: buildings?.length ?? 0,
            itemBuilder: (BuildContext ctxt, int index) {  
              return InkWell(
                  onTap: () => _handleRowTap(buildings[index].id),
                  child: Padding(
                    padding: EdgeInsets.all(8),
                    child: Text(
                          "${buildings[index].buildingName}",
                        ),
                  ));
            }));

И последняя.

_handleRowTap(String buildingId) {
//Handle click event here
  }
0 голосов
/ 05 августа 2020

Вот отличное руководство о том, как json и сериализация работают во Flutter: https://flutter.dev/docs/development/data-and-backend/json

В основном вы создаете модель для своей структуры данных:

class Entity {
   int entityId;
   String buildingName;
   String location;
   String imageField;

   Entity({this.entityId, this.buildingName, this.location, this.imageField});

   Entity.fromJson(Map<String, dynamic> json) : 
     entityId = json["entity_id"],
     buildingName = json["building_name"],
     location = json["location"],
     imageField = json["imageField"];
}

Когда вы это сделаете, вы можете десериализовать свой json следующим образом, используя пакет dart: convert:

var jsonMap = jsonDecode(jsonString);
var entity = Entity.fromJson(jsonMap);

После этого вы можете поместить свою сущность в качестве данных для выбора в раскрывающемся списке. И при выборе «Бурдж-Халифа». Вы можете просто проверить entity.id

0 голосов
/ 05 августа 2020
 DropdownButtonFormField(
      hint: Text("Building"),
      onChanged: ((val) {
        setState((){
        print(val. entity_id);
        selectedBuilding = val;
        });
      }),
      value: selectedBuilding ?? null,
      items: buildingList.map<DropdownMenuItem>((BuildingModel value) {
        return DropdownMenuItem(
          value: value,
          child: Text(value.building_name),
        );
      }).toList(),
      decoration: InputDecoration(
        icon: Icon(Icons.access_time)
      ),
    );

Вы можете получить выбранную вами модель здания:

onChanged: ((val) {
            setState((){
          print(val. entity_id);
          selectedBuilding = val;
          });
          }),
0 голосов
/ 05 августа 2020

вы можете использовать foreach для доступа к каждому элементу списка, например

decoded.forEach((element) { 
  var entity_id = element['entity_id'];
})

В вашем случае, когда вы нажимаете кнопку раскрывающегося списка, вы получите индекс элемента, используйте этот индекс и получите его следующим образом

var entity_id = decoded.elementAt(index)['entity_id'];
...