Home > Software design >  How to read JSON from an API in Flutter?
How to read JSON from an API in Flutter?

Time:04-21

First the API call:

pegar() async {
  var url = Uri.parse("http://localhost/luis/listar.php?id=45");
  var response = await http.get(url);
  var json = jsonDecode(response.body);
  return json;
}

The API returns this JSON

[{
"id":"5",
"numero":"45",
"nome":"Adriana da Silva",
"titulo":"123456789012",
"foto":"foto2.jpg"
}]

When the field is filled, it calls the API method, but it has an error reading the result

TextFormField(
controller: _pCandidato,
decoration: InputDecoration(
  border: OutlineInputBorder(),
  labelText: "Candidato",
),
style: TextStyle(fontSize: 30),
maxLength: 2,
onChanged: (value){
  if(value.length==2){
    condicao=true;
    
    setState(() async {
      final json = await pegar();
      print(json["id"]);    // HERE THE ERROR OCCURS
    });
  }
},

THE ERROR:

The following assertion was thrown while calling onChanged: setState() callback argument returned a Future.

The setState() method on _VotacaoState#2f314 was called with a closure or method that returned a Future. Maybe it is marked as "async".

Instead of performing asynchronous work inside a call to setState(), first execute the work (without updating the widget state), and then synchronously update the state inside a call to setState().

CodePudding user response:

try print(json[0]["id"]);

CodePudding user response:

You cannot do a setstate on a future. You first have to get data from a future and then do setstate

final json = await pegar();
setState(()  {
      
      print(json["id"]);    
    });

CodePudding user response:

Update the code following:

onChanged: (value) async { // async here
  if(value.length == 2){
    condicao=true;
    final json = await pegar(); // get the json before call setState
    
    setState(() { // dont async setState
      print(json["id"]);
    });
  }
}
  • Related