Can I pass a BuildContext to Compute?
Asked Answered
A

1

7

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!

Afar answered 10/11, 2019 at 19:50 Comment(3)
the question is: why would you want to do that?Nyx
My code computes something complex using BuildContext.Afar
so you have to change it so that it does not use BuildContextNyx
W
4

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.

Willett answered 10/11, 2019 at 20:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.