dart - 在主线程上执行Flutter异步

标签 dart async-await

我有一个填满整个屏幕的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/

相关文章:

c# - 在 ASP.NET 中轮询 Google Big Query 结果期间调用 Thread.Sleep 是否合适?备择方案?

mysql - 实现 async/await node.js 和 mysql

javascript - 如何调用多个函数之一 - JavaScript?

audio - flutter ( Dart ): Get/Record audio stream from microphone and play it back immediately (real-time)

C# - 通过网络流接收文件会阻塞 WPF UI

unit-testing - 我应该如何在 Dart 中测试 Future?

dart - 在 flutter 中使用新关键字

flutter - 如何在不存在于同一文件中的两个小部件之间传递文本值

dart - 从类实例调用时,映射值是私有(private)的