【问题标题】:await doesnt work with stream for me in flutter等待不适用于我的流
【发布时间】:2020-12-13 16:10:24
【问题描述】:

我有一个问题,我想从数据库中读取一些数据,我希望我的函数在继续执行我的其余代码之前等待数据。我正在使用带有 await 和 async 的流,但看起来它不适合我。

这是我的代码

void updateIncome() async {
     Stream<List<IncomeData>> _currentEntries;
     _currentEntries =  database.watchIncomeForUpdate(this.income);
    await _currentEntries.forEach((List<IncomeData> x) {
        x.forEach((element) {
          print('AWAIT');
        }
        );
      });
      print('FINISH');
  }

这是调用我的数据库并获取数据的过程

Stream<List<IncomeData>> watchIncomeForUpdate(IncomeData entry)  {
   return  (select(income)..where((t) =>t.id.isBiggerOrEqualValue(entry.id) & t.groupId.equals(entry.groupId))
     ..orderBy([(t) => OrderingTerm(expression: t.dateReceived)])).watch();
  }

当我运行函数 updateIncome() 时,它首先打印 FINISH,这让我相信等待 foreach 循环遍历列表中的所有元素,等待/异步不起作用。
我试图在函数调用中移动 await 关键字

_currentEntries =  await database.watchIncomeForUpdate(this.income);

我收到一条警告消息:await 应用于 Stream 我不是 Future 有人能帮我吗?我做错了什么?

我想等待数据库获取数据,循环并打印 AWAIT,然后当完成时,它应该继续执行其余代码并打印 FINISH。调用数据库的函数返回 8 行。所以当我使用 foreach 循环时,它应该打印 AWAIT 8 次,然后是 FINISH。

如何修复我的代码,以便函数调用数据库,循环遍历元素并等待循环完成,然后再继续执行循环外的其余代码?

【问题讨论】:

  • await 在 forEach 中不起作用
  • 你为什么用watch而不是get
  • 嗨,Richard,我使用 watch 是因为我希望流在我的数据库中查找更改并获取这些更改。例如,假设我读取了我的数据库并在小部件中显示我的数据。然后我在数据库中进行更改,然后 watch 应该查找任何更改。如果这不是它的工作原理,你能解释一下两者之间的区别,我什么时候可以使用手表,什么时候使用get?还有,你知道问题的解决方法吗

标签: flutter


【解决方案1】:

由于 watchIncomeForUpdate 不是 Future 函数,您不能等待非未来函数。

void updateIncome() async {
    await for(var x in database.watchIncomeForUpdate(this.income)){
        x.forEach((element) {
          print('AWAIT');
        }
        );
      });
      print('FINISH');
  }

参考:https://dart.dev/tutorials/language/streams

【讨论】:

    【解决方案2】:

    感谢所有回复。我想通了。
    我从这里改变了功能

    Stream<List<IncomeData>> watchIncomeForUpdate(IncomeData entry)  {
       return  (select(income)..where((t) =>t.id.isBiggerOrEqualValue(entry.id) & t.groupId.equals(entry.groupId))
         ..orderBy([(t) => OrderingTerm(expression: t.dateReceived)])).watch();
      }
    
    

    到这里

     Future<List<IncomeData>>  watchIncomeForUpdate(IncomeData entry)  async {
       return  (select(income)..where((t) =>t.id.isBiggerOrEqualValue(entry.id) & t.groupId.equals(entry.groupId))
         ..orderBy([(t) => OrderingTerm(expression: t.dateReceived)])).get();
      }
    

    然后调用过程为

          data = await database.watchIncomeForUpdate(this.income);
    
    

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2016-03-21
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多