Can I pass a BuildContext to Compute?

天大地大妈咪最大 提交于 2020-03-22 09:04:15

问题


Is it possible to use BuildContext inside compute function?

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

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

I receive the following error when attempting to pass the context to compute:

I/flutter ( 8764): AsyncSnapshot<int>(ConnectionState.done, null, Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function '_handleBuildScheduled@374399801':.))

If I change the input to the count function to other normal class, it works fine.

Is there any way to fix this? Or is using BuildContext possible in an Isolate? Thanks!


回答1:


As explained in the documentation, no - you cannot send a BuildContext to a compute function, i.e. another Isolate (compute is only a wrapper for simple isolates).

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.

The message is the value of Q (R is the return value) and is therefore subject to the following limitations:

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.


If you want to learn more about isolates in general, the Flutter team published a video about working with Isolates in Flutter. They also explain how isolates work on a lower level, which might be useful to you in understanding why these limitations are in place.



来源:https://stackoverflow.com/questions/58792351/can-i-pass-a-buildcontext-to-compute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!