【问题标题】:Using Future<List<T>> in Future.wait在 Future.wait 中使用 Future<List<T>>
【发布时间】:2023-02-22 18:54:45
【问题描述】:

我正在从 Flutter 中的 API 获取数据。数据来自多个 API,因此我使用 Future.wait 使其更流畅。我有这个变量:

late List<Cast> castMembers;

这个功能:

 Future<List<Cast>> getCast() async {
    List<Cast> members= [];
    // here is the logic of serialization etc...
    return members;
  }

最后是一个带有 Future.wait 的函数:

Future<void> callApi() async{
await Future.wait([       
        getAdresses(),
        getCountries(),  
        getPrices(),
        castMembers=await getCast()
      ]);
}

这样我就出错了。如果我将 castMembers=await getCast() 放在 Future.wait 之前它工作正常,但在这种情况下,在我们等待 getCast() 时,Future.wait 内的方法将不会执行。

你对此有何建议?

【问题讨论】:

  • 使用Future.wait方法返回的值,文档说:“返回的未来的价值将是按照迭代期货提供期货的顺序产生的所有值的列表”

标签: flutter dart


【解决方案1】:

不应将字段 castMembers 作为数组的成员,因为它不是 Future

当您键入 castMembers=await getCast() 时,它计算 getCast(),将其值放入 castMembers,并将该值添加到列表中。

换句话说,你应该有:

class A {
  late List<Cast> castMembers;

  Future<void> callApi() async {
    await Future.wait([
      getAdresses(),
      getCountries(),
      getPrices(),
      getCast(),
    ]);
  }

  Future<List<Cast>> getCast() async {
    List<Cast> members = [];
    return members;
  }

  Future<String> getAdresses() async => '';

  Future<int> getCountries() async => 1;

  Future<List<double>> getPrices() async => List.of();
}

class Cast {}

代替

await Future.wait([       
  getAdresses(),
  getCountries(),  
  getPrices(),
  castMembers=await getCast()
]);

如果要初始化变量,请单独执行:

castMembers = await getCast();
await Future.wait([
  getAdresses(),
  getCountries(),
  getPrices(),
]);

【讨论】:

猜你喜欢
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 2016-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多