是否可以在 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 ,不 - 您不能发送 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
是返回值),因此受到以下限制: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/