dartdart-isolates

Can a closure be sent to a SendPort


I'm working on implementation two-isolates app. In this scope I'm exploring a possibility to send a closure via SendPort. The documentation says that in case isolates share same code anything can be sent with some exceptions. But when I try to call this

port.send(() {});

I get an error:

E/flutter (26634): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function '':.)

Is that expected behavior and one just can't send functions via SendPort?

My environment is:

Flutter 3.3.9 • channel stable • https://github.com/flutter/flutter.git
Framework • revision b8f7f1f986 (6 months ago) • 2022-11-23 06:43:51 +0900
Engine • revision 8f2221fbef
Tools • Dart 2.18.5 • DevTools 2.15.0

Solution

  • Since Dart 2.15, which enables isolate groups by default, isolates started with Isolate.spawn() share the same code and allow including closures in inter-isolate messages.

    This may fail if the closure's enclosing context contains messages that are not sendable. Sending closures to isolates is generally discouraged due to this issue. See dart-lang/sdk#36983, where this is discussed in relation to another issue.

    See the Dart VM section of the Dart 2.15.0 changelog for more information.