I understand that isolates in Dart run in separate memory spaces and communicate via message passing and I should serialize these objects first before sending them to the isolate, but I found a strange behavior while using the isolate in a closure, here is my example:
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Closure and Isolate Example')),
body: Center(
child: ElevatedButton(
onPressed: () async {
final a = Text("TEXT");
await Isolate.spawn((_) {
print(a);
}, []);
},
child: Text('Run Isolate'),
),
),
);
}
}
This example worked and printed the widget, but if I put this line outside the onPressed
final a = Text("TEXT");
it throws an error:
`E/flutter (25736): <- Instance of 'WidgetsFlutterBinding' (from package:flutter/src/widgets/binding.dart)
E/flutter (25736): <- field this in SemanticsBinding._handleSemanticsActionEvent (from package:flutter/src/widgets/binding.dart)
E/flutter (25736): <- _onSystemFontFamilyChangedZone in Instance of 'PlatformDispatcher' (from dart:ui)
E/flutter (25736): <- platformDispatcher in Instance of 'FlutterView' (from dart:ui)
...
so I can use any object from the closure in the isolate and it will work, no matter how complex this object is, how this happens?