setState() callback argument returned a Future in flutter

Viewed 2941

I'm trying to run a statment with await inside a setState block, I added it inside another Future<void> function but still I need to add async on the setState to be able to run it .

here is my code :

setState(() async {
  chosenStations.clear();
  chosenStations.add(allStations[
  suggestions.indexOf(fromLocationName)]);
  _loading = true;
  chosenStations.add(allStations[
  suggestions.indexOf(toLocationName)]);
  await showingLines();
      });


  Future<void> showingLines() async {
    theLines.clear();
    theLines = await DatabaseServices().fetchingLinesData(
        chosenStations[0], chosenStations[1]);
  }

and I got this error :

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

The error tells that you need to move all the asynchronous logic out of setState because setState used to update the UI after doing some work apart of its nature

so what you can do is to move the showingLines function out of setState and await it then update the UI with the new lines

await showingLines();
setState(() {
      chosenStations.clear();
      chosenStations.add(allStations[
      suggestions.indexOf(fromLocationName)]);
      _loading = true;
      chosenStations.add(allStations[
      suggestions.indexOf(toLocationName)]);
  });


Future<void> showingLines() async {
    theLines.clear();
    theLines = await DatabaseServices().fetchingLinesData(
        chosenStations[0], chosenStations[1]);
}

Note: you can use setState directly without filling it with any work,

await showingLines();
chosenStations.clear();
chosenStations.add(allStations[
suggestions.indexOf(fromLocationName)]);
_loading = true;
chosenStations.add(allStations[
suggestions.indexOf(toLocationName)]);

setState(() {});

Future<void> showingLines() async {
    theLines.clear();
    theLines = await DatabaseServices().fetchingLinesData(
        chosenStations[0], chosenStations[1]);
}
Related