我可以将 BuildContext 传递给 Compute 吗?
Can I pass a BuildContext to Compute?
是否可以在 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':.))
如果我将计数函数的输入更改为其他正常 class,它工作正常。
有什么办法可以解决这个问题吗?
或者是否可以在 Isolate 中使用 BuildContext?
谢谢!
作为 explained in the documentation,不 - 你不能将 BuildContext
发送到 compute
函数,即另一个 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.
message
是 Q
的值(R
是 return 的值),因此受到以下限制:
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.
如果您想了解更多有关 isolates 的一般知识,Flutter 团队发布了一篇 video about working with Isolate
s in Flutter。他们还解释了 isolate 如何在较低级别上工作,这可能有助于您理解为什么存在这些限制。
是否可以在 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':.))
如果我将计数函数的输入更改为其他正常 class,它工作正常。
有什么办法可以解决这个问题吗? 或者是否可以在 Isolate 中使用 BuildContext? 谢谢!
作为 explained in the documentation,不 - 你不能将 BuildContext
发送到 compute
函数,即另一个 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.
message
是 Q
的值(R
是 return 的值),因此受到以下限制:
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.
如果您想了解更多有关 isolates 的一般知识,Flutter 团队发布了一篇 video about working with Isolate
s in Flutter。他们还解释了 isolate 如何在较低级别上工作,这可能有助于您理解为什么存在这些限制。