问题
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