Flutter can you "send" objects as a message with compute()?

Viewed 2107

So I basically have a simple class with a update() method. But because that update() method makes some math, I wanted to use compute() to make it run in another Isolate. The plan was to run the update() method in the Isolate and return the updated object like this:

compute(updateAsset, asset).then((value) => asset = value);

Asset updateAsset(Asset asset) {
  asset.update();
  return asset;
}

But then I get this error:

ArgumentError (Invalid argument(s): Illegal argument in isolate message : (object extends NativeWrapper - Library:'dart:ui' Class: Path))

Is there any possible way to send an object to an Isolate or do I have to send every single Value of that Asset as an Integer, create a new Object and return that?

1 Answers

According to the docs:

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.

So I see a 2 options that you can use.

  1. You can send every value as an integer or other primitive in a Map or List if it's possible for your object to be deconstructed like that.
  2. If that method is too difficult for any reason, you can instead convert you object to a primitive type, the easiest being String with JSON encoding. You can encode your object with the jsonEncode function and send the String that it returns over to your isolate where you would then decode it back to your object if necessary.
Related