android - setState() 回调参数在 flutter 中返回了一个 Future

标签 android ios flutter asynchronous dart

我正在尝试在 setState 中运行带有 await 的语句 block ,我将它添加到另一个 Future<void> 中功能,但我仍然需要添加 asyncsetState 上能够运行它。

这是我的代码:

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/

相关文章:

android - 上传 key 与部署 key 相同。出于安全原因,我们需要它们不同。请使用不同的上传证书

android - Git 预提交钩子(Hook)运行 lint 检查?

ios - 从 UIWebview 保存的 URL 与 True Url 不对应

ios - 为什么我的视频没有显示在我使用 AVPlayer 的 ScrollView 中的单元格中

当文本大于输入时 flutter ,文本消失

android - 为什么不同的 Activity 在 Android 中显示为单独的应用程序

ios - 用于简化 Objective C 中的 Singleton 方法调用的宏,以执行类似 NSLocalizedString 的操作

flutter - Flutter 中的 IOS 日期选择器

Flutter 为 Web 构建 - "Failed to compile application"

java - 如何将 .dll 导入 Android java 项目(使用 eclipse)