Hii There is a mistake in your code. As far as I know from the official documentation The callback method for an Isolate should be a top level function or a static
method.
So there are two solution for this problem.
Solution 1. declare callback function as top level function.
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({Key? key, required this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: TextButton(
child: const Text("Run Isolate"),
onPressed: _onPressed,
));
);
}
// Callback function for Text Button Event this should be a class member
void _onPressed() async {
var receivePort = ReceivePort();
// Here runMyIsolate methos should be a top level function
await Isolate.spawn(runMyIsolate, [receivePort.sendPort, "My Custom Message"]);
print(await receivePort.first);
}
}
// We declare a top level function here for an isolated callback function
void runMyIsolate(List<dynamic> args) {
var sendPort = args[0] as SendPort;
print("In runMyIsolate ");
Isolate.exit(sendPort, args);
}
Solution 2. instead this top level function we can declare this
function as a static
function for the same class, consider below
example.
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({Key? key, required this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: TextButton(
child: const Text("Run Isolate"),
onPressed: _onPressed,
));
);
}
// Callback function for Text Button Event this should be a class member
void _onPressed() async {
var receivePort = ReceivePort();
// Here runMyIsolate methos should be a top level function
await Isolate.spawn(runMyIsolate, [receivePort.sendPort, "My Custom Message"]);
print(await receivePort.first);
}
// We declare a static function here for an isolated callback function
static void runMyIsolate(List<dynamic> args) {
var sendPort = args[0] as SendPort;
print("In runMyIsolate ");
Isolate.exit(sendPort, args);
}
}
void onPressed() async { await Isolate.spawn(gotoNext, "OK"); } void gotoNext(String args) { log(args); }
– RomyPath
object? – Bloomingtonvoid onPressed() async { var receivePort = ReceivePort(); await Isolate.spawn(gotoNext, [receivePort.sendPort]); final msg = await receivePort.first; print('received >$msg<'); } void gotoNext(List<dynamic> args) { SendPort sendPort = args[0]; print('>input parameters: $args<'); Isolate.exit(sendPort, "OK"); }
and this is what i see on the logs after callingonPressed
function:[+5088 ms] flutter: >input parameters: [SendPort]< [ +12 ms] flutter: received >OK<
– BloomingtonFlutter 2.11.0-0.1.pre • channel beta • https://github.com/flutter/flutter.git Framework • revision b101bfe32f (3 weeks ago) • 2022-02-16 07:36:54 -0800 Engine • revision e355993572 Tools • Dart 2.17.0 (build 2.17.0-69.2.beta) • DevTools 2.10.0-dev.1
– Bloomington