如何在包含异步的函数返回的值上使用List.sort? [英] How to use List.sort on values returned from a function that contains an async?

查看:77
本文介绍了如何在包含异步的函数返回的值上使用List.sort?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

 widget.items.sort((a, b) {

           await getItemDistance(a, true);
          await getItemDistance(b, false);

          return (itemADistance)
              .compareTo(itemBDistance);
        });

我正在尝试基于从getItemDistance返回的值对widget.items列表进行排序.但是我看到一条红色的波浪线,显示错误:

I am trying to sort widget.items list based on values returned from getItemDistance. However I get an error with a red squiggly line that says :

await表达式只能在异步函数中使用

The await expression can only be used in an async function

,当我尝试将async添加到sort方法时,我又得到一条红色的波浪线,它表示:

and when I try to add async to the sort method I get another red squiggly line that says :

不能分配参数类型'Future Function(Item,Item)'参数类型为'int Function(Item,Item)'

The argument type 'Future Function(Item, Item)' can't be assigned to the parameter type 'int Function(Item, Item)'

我该如何解决这个难题?:)谢谢

How do I solve this dilemma guys ? :) Thanks

推荐答案

List.sort 是一个同步函数,需要同步回调.没有办法将其与异步回调一起使用.我建议转换您的 List 并进行必要的异步工作 first then 同步对结果进行排序.这样做还应避免在同一项目上多次调用 getItemDistance (由于异步,它可能很昂贵).例如,类似:

List.sort is a synchronous function that expects a synchronous callback; there is no way to use it with an asynchronous callback. I would recommend transforming your List and doing any necessary asynchronous work first and then synchronously sorting the results. Doing so also should avoid calling getItemDistance (which, by virtue of being asynchronous, is likely to be expensive) on the same item multiple times. For example, something like:

final computedDistances = <Item, double>{};
for (final item in widget.items) {
  final distance = await getItemDistance(item, ...);
  computedDistances[item] = distance;
}

widget.items.sort((a, b) => 
  computedDistances[a].compareTo(computedDistances[b])
);

(我不知道 getItemDistance 的第二个参数代表什么;如果无法解决,您将需要使用 Map > getItemDistance(...,true)结果,而其中一个具有 getItemDistance(...,false)结果.)

(I don't know what the second argument to getItemDistance represents; if you can't get around that, you would need to build one Map with getItemDistance(..., true) results and one with getItemDistance(..., false) results.)

作为最后的选择,您可以编写自己的异步排序函数.

As a last resort, you could write your own asynchronous sort function.

修改

这应该是一个更有效的版本,因为它不会等待每个异步操作一个一个地

This should be a more efficient version since it doesn't wait for each asynchronous operation one-by-one:

final computedDistances = await Future.wait<double>([
  for (final item in widget.items) getItemDistance(item, ...),
]);

final computedDistancesMap = <Item, double>{
  for (var i = 0; i < widget.items.length; i += 1)
    widget.items[i]: computedDistances[i],
};

widget.items.sort((a, b) => 
  computedDistancesMap[a].compareTo(computedDistancesMap[b])
);

这篇关于如何在包含异步的函数返回的值上使用List.sort?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆