我正在尝试在 setState
中运行带有 await 的语句 block ,我将它添加到另一个 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]);
}
我得到了这个错误:
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().
最佳答案
该错误表明您需要将所有异步逻辑从 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]);
}
注意:可以直接使用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]);
}
关于android - setState() 回调参数在 flutter 中返回了一个 Future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61175917/