Snippets Collections
import 'dart:async';
import 'dart:isolate';
main() async {
  var receivePort = new ReceivePort();
  await Isolate.spawn(echo, receivePort.sendPort);
// The 'echo' isolate sends it's SendPort as the first message
  var sendPort = await receivePort.first;
var msg = await sendReceive(sendPort, "bye");
  print('received $msg');
  msg = await sendReceive(sendPort, "hello");
  print('received $msg');
}
// the entry point for the isolate
echo(SendPort sendPort) async {
  // Open the ReceivePort for incoming messages.
  var port = new ReceivePort();
// Notify any other isolates what port this isolate listens to.
  sendPort.send(port.sendPort);
await for (var msg in port) {
    var data = msg[0];
    SendPort replyTo = msg[1];
    replyTo.send(data);
    if (data == "hello") port.close();
  }
}
/// sends a message on a port, receives the response,
/// and returns the message
Future sendReceive(SendPort port, msg) {
  ReceivePort response = new ReceivePort();
  port.send([msg, response.sendPort]);
  return response.first;
}
star

Fri Aug 27 2021 05:28:55 GMT+0000 (Coordinated Universal Time) https://medium.com/flutterdevs/threading-in-flutter-e5b84c7d8d31

#flutter #dart #threading

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension