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().