我有一个填满整个屏幕的CameraPreview
,在底部有一个FloatingActionButton
来拍照。
在该按钮的onPress
方法上,我正在进行网络调用,该网络调用我不关心(尚未)结果。因此,我希望在该方法内部进行的所有操作均以异步方式完成,因此它不会阻塞我的主线程。
这意味着(如果我理解正确的话)我不会使用await
关键字。
这是我的onPressed
中的代码
// Attempt to take a picture and log where it's been saved
await controller.takePicture(path);
print("Done taking picture");
sendBase64ToAPI(path);
这是我的
sendBase64ToApi
方法Future<String> sendBase64ToAPI(String path) async {
File(path).readAsBytes().then(thenMethod);
return null;
}
void thenMethod(List bytes){
print("Start reading file");
Image image = decodeImage(bytes);
int x = ((screenWidth/2) + (overlayWidth/2)).toInt();
int y = ((screenHeight/2) + (overlayHeight/2)).toInt();
print("Start cropping image");
image = copyCrop(image, x, y, overlayWidth, overlayHeight);
var base64Str = base64.encode(image.getBytes());
print("Done");
print(base64Str.substring(0,30));
print(base64Str.substring(base64Str.length-30,base64Str.length-1));
}
我的UI完全冻结在“开始读取文件”和“开始裁剪图像”之间,尽管它们是异步方法,在没有
await
的情况下调用,因此不应该发生。为什么这些方法不异步执行?
最佳答案
好的,我正在使用的库中的this seems to be a known issue。
该文档建议在decodeImage
中使用Isolate
函数。
如果有人在我的代码中发现了同步的内容,那么这个问题将持续几天。
关于dart - 在主线程上执行Flutter异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55908972/