Ahm*_*gdi 3 android asynchronous ios dart flutter
我正在尝试在setState块内运行带有等待的语句,我将其添加到另一个Future<void>函数中,但我仍然需要添加async才能setState运行它。
这是我的代码:
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]);
}
Run Code Online (Sandbox Code Playgroud)
我得到了这个错误:
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().
Run Code Online (Sandbox Code Playgroud)
该错误表明您需要将所有异步逻辑移出setState,因为setState用于在完成一些与其性质无关的工作后更新 UI
所以你可以做的就是将该showingLines函数移出setState并等待它,然后用新行更新 UI
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]);
}
Run Code Online (Sandbox Code Playgroud)
setState注:无需填写任何工作即可直接使用,
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]);
}
Run Code Online (Sandbox Code Playgroud)