CodeBlanks Logo Icon CodeBlanks

SendPort

Learn communication with SendPort and ReceivePort.

SendPort and ReceivePort

ReceivePort is the channel opened to receive messages. SendPort is the endpoint used to send messages into it. It is obtained via receivePort.sendPort.

Typical flow: the main isolate opens a ReceivePort, passes its sendPort to spawn. The new isolate, when done, replies with sendPort.send(result).

ReceivePort is a Stream; you wait for messages with await for or .first. When done, close it with close().

Two-way communication

For two-way communication between two isolates, each side opens a ReceivePort and sends its sendPort to the other. Each side can then send messages to the other.

Messages are processed in order; a single port receives one message at a time. No extra synchronization is needed.

Large objects are copied; for very large data, TransferableTypedData gives zero-copy transfer.

Practice Wait for a message with ReceivePort

Make main async. Open a port with var port = ReceivePort();. Send a message to it with port.sendPort.send('merhaba isolate'). Wait for the first message with var msg = await port.first; and print it with print(msg);.

Starter code

main.dart
void main() {
  // make async; open ReceivePort; sendPort.send a message; await first message
}

Sample solution

main.dart
import 'dart:isolate';

void main() async {
  var port = ReceivePort();
  port.sendPort.send('merhaba isolate');
  var msg = await port.first;
  print(msg);
}

Expected output

merhaba isolate

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the port concepts

Term Meaning
ReceivePort Message receiving channel
SendPort Message sending endpoint
.sendPort SendPort accessor
.first First message

2 Which interface does ReceivePort implement?

  • Future
  • Iterable
  • Stream Correct answer
  • Isolate

Explanation: ReceivePort is a Stream, yielding messages as a flow.

3 Sending a message

Question
sendPort.____('merhaba');
Answer
sendPort.send('merhaba');

Explanation: SendPort.send sends a message.

All lessons in Advanced