Popular Dropdown with api

Asked

Viewed 205 times

0

Hello, I am trying to recover the json data from a URL, I am following this tutorial

https://inducesmile.com/google-flutter/how-to-populate-dropdownbutton-using-json-api-in-flutter/ I was able to reproduce successfully.

But with my Json url I’m in trouble. Json is a little different;

Tutorial Json Format

[{"id": 1, "name": "Leanne Graham"},{"id": 2,"name": "Ervin Howell"}]

Json format my URL

{"data":[{ "id":1, "name":"Acre" }, { "id":2, "name":"Alagoas" }]}

This is the part where I’m in trouble

final items = json.decode(response.body).cast<Map<String, dynamic>>();

As following error:

NoSuchMethodError (NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.

1 answer

1


I answered a similar question a few days ago, you can rely on it to fix your problem by making a small change...

That’s my answer to another question How to compare Map and Json value in flutter?

Let’s see what it would look like in your case

Create the class that will receive the data of each object of your JSON

class Dados {
    String name;
    String id;

    Conta({
      this.name,
      this.id
    });

    factory Dados.fromJson(Map<String, dynamic> json) => Dados(
        name: json["name"],
        id: json["id"]
    );
}

To get the data from your JSON do the following

class Items{
  String json = '{"data":[{ "id":1, "name":"Acre" }, { "id":2, "name":"Alagoas" }]}';
  List<Dados> dados;

  void PegarDados(){
    final jsonMap = jsonDecode(json);
    dados = (jsonMap["data"] as List).map((item) => Dados.fromJson(item)).toList();  
  }

  void ClasseMontarItens(){
    PegarDados();
    var primeiroDadoId = dados[0].id;
    var primeiroDadoNome = dados[0].name;

    print("Esse é o primeiro item: $primeiroDadoId - $primeiroDadoNome");
  }
}
  • Hello Matheus, I tested your code, , and this error occurs; Only Static Members can be accessed in initializers.Dart(implicit_this_reference_in_initializer) final jsonMap = jsonDecode(json);

  • You are probably trying to create this variable final jsonMap = jsonDecode(json); directly in your class, try to put it within a method or just declare it as var jsonMap; and then where you receive the value of the JSON do jsonMap = jsonDecode(json);

  • @Luiz improved my example, see if it is now clearer!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.