0

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

  • This is similar to question https://stackoverflow.com/questions/69832046/how-to-use-the-free-and-public-rapid-api-and-call-the-api-in-the-flutter-applica/69834832#69834832 – Roslan Amir Apr 20 '22 at 01:44
  • You can do set state after retrieve value as per error set state is returning future. you can make onChanged: (value) async { } and then just retrieve value and don't do setstate – Hardik Mehta Apr 20 '22 at 04:41

3 Answers3

0

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"]);    
    });

griffins
  • 7,079
  • 4
  • 29
  • 54
0

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

HamZa
  • 71
  • 6
0

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"]);
    });
  }
}
Tuan
  • 2,033
  • 1
  • 9
  • 16