flutter - 我可以将 BuildContext 传递给 Compute 吗?

标签 flutter dart dart-isolates

是否可以在 compute 中使用 BuildContext功能?

Future<int> getFuture() async {
  int r = await compute(count, context);
  return r;
}

static int count(BuildContext context) {
  // Something very slow.
  return 10;
}

我在尝试传递 context 时收到以下错误至 compute :
I/flutter ( 8764): AsyncSnapshot<int>(ConnectionState.done, null, Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function '_handleBuildScheduled@374399801':.))

如果我将 count 函数的输入更改为其他普通类,它可以正常工作。

有没有什么办法解决这一问题?
或者在 Isolate 中使用 BuildContext 可能?
谢谢!

最佳答案

explained in the documentation ,不 - 您不能发送 BuildContextcompute函数,即另一个 Isolate ( compute 只是简单隔离的包装器)。

There are limitations on the values that can be sent and received to and from isolates. These limitations constrain the values of Q and R that are possible. See the discussion at SendPort.send.


messageQ 的值( R 是返回值),因此受到以下限制:

The content of message can be: primitive values (null, num, bool, double, String), instances of SendPort, and lists and maps whose elements are any of these. List and maps are also allowed to be cyclic.



如果您想了解更多关于隔离的一般信息,Flutter 团队发布了 video about working with Isolate s in Flutter .他们还解释了隔离如何在较低级别上工作,这可能有助于您理解为什么存在这些限制。

关于flutter - 我可以将 BuildContext 传递给 Compute 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58792351/

相关文章:

forms - 手动设置Flutter验证错误

Flutter Android 应用程序在启动时崩溃且没有错误

dart - 我可以在 Dart 中不使用任何构造函数来获取类的 InstanceMirror 吗?

dart - 关于 Dart Isolates 的最新文档

global-variables - 使用全局变量在 Dart 中的函数之间共享对象是否安全?

flutter - 两个isolate通过端口发送消息会丢弃dart 2.5版本的一些消息

flutter - 如果路径或名称文件中存在空格,则无法加载图像 Flutter

firebase - 如何在flutter中检查数据是否已成功写入Firebase

android - 无法找到Flutter项目的lint-gradle-api-26.1.2.jar

sharedpreferences - Flutter Shared Preferences 保存值,不显示