【发布时间】:2020-10-25 03:17:32
【问题描述】:
我正在开发一个捕获和处理图像的应用程序。代码的简化版本是:
build() {
return FloatingActionButton(
onPressed: processImage,
child: Icon(
Icons.camera_alt,
color: color,
),
);
}
processImage(Camera image) async {
await image.process();
}
在另一个班级:
Future<image> process() {
return Future(() {
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
//process image
}
}
});
}
但是当process() 运行时,UI 会冻结。
为什么会这样?传递给Future构造函数的那个函数不是在后台运行吗?
【问题讨论】:
-
我不是 100% 确定,但我知道 dart 使用事件循环并且一切都将在主线程上运行(可能在将来的某个时间点,在异步代码的情况下) .因此,该代码最终将在主线程上执行,从而导致阻塞。考虑使用 Dart 的分离器;那应该可以解决问题。 Flutter 有一个内置的便捷方法可以为您执行此操作,但我不记得它叫什么。
-
@GregoryConrad 谢谢,这对我有用,不是一个非常优雅的解决方案,但它有效,如果你想把它作为一个答案,我很乐意把它作为正确的答案
-
compute()函数中什么不是“优雅”? -
@pskink 我的函数接收6个参数,你不能调用一个类方法:
"The callback argument must be a top-level function, not a closure or an instance or static method of a class",你只能传递一个参数,所以我不得不把我所有的参数都转换成一个Map<String, dynamic>,创建一个接收映射的顶级函数,并解构为原始变量。