在主线程上执行颤动异步

问题描述 投票:1回答:1

我有一个填充整个屏幕的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的情况下调用,因此不应该发生。

为什么这些方法不是异步执行的?

dart async-await
1个回答
0
投票

好吧,来自我正在使用的图书馆的this seems to be a known issue

文档建议在decodeImage中使用Isolate函数。

如果有人发现我的代码中同步的内容,请将问题保持开放几天。

© www.soinside.com 2019 - 2024. All rights reserved.