【问题标题】:setState() callback argument returned a Future in fluttersetState() 回调参数在颤动中返回了一个 Future
【发布时间】:2020-07-25 07:19:45
【问题描述】:

我正在尝试在 setState 块内运行带有 await 的语句,我将它添加到另一个 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().

【问题讨论】:

    标签: android ios flutter asynchronous dart


    【解决方案1】:

    该错误表明您需要将所有异步逻辑移出 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]);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-13
      • 2019-11-18
      • 2020-02-07
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 2021-01-18
      相关资源
      最近更新 更多