我试图在setState
块中运行一个带有wait的语句,我在另一个Future<void>
函数中添加了它,但我仍然需要在setState
上添加async
才能运行它。
这是我的代码:
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]);
}