Sitemap

Dart Isolate Tips

2 min readMar 19, 2024

--

Press enter or click to view image in full size

    Get Chencwf’s stories in your inbox

    Join Medium for free to get updates from this writer.

  1. Isolates do not share memory, so you cannot use a dart singleton to share information between isolates.
  2. If you want to debug code inside an isolate, a hot-restart is useless; you must do a cold start because it is a native thread.
  3. Isolates communicate using Ports, and the logic for using Ports is as follows (from https://dart.dev/language/isolates):
  • a. The initiating thread first creates a ReceivePort. The purpose of the ReceivePort is for the initiating thread to listen to messages sent by other threads. If the initiating thread wants to actively send messages to other threads, then the sender needs a SendPort from the receiver. With the receiver’s SendPort, messages can be sent to the receiver.
  • b. Therefore, when the initiating thread spawns a thread, it passes its own ReceivePort.sendPort as an argument to the passive thread.
  • c. The passive thread obtains the SendPort sent by the initiating thread from the arguments, allowing the passive thread to send messages to the initiating thread.
  • d. For the passive thread to allow the initiating thread to also send messages to it, it must also create a ReceivePort. Then, through the initiating thread’s SendPort, it sends its own ReceivePort.sendPort as the first message to the initiating thread in advance. At the same time, it listens for messages from the initiating thread through this ReceivePort.listen.
  • e. The initiating thread will first receive the SendPort message sent by the passive thread through its own previously created ReceivePort.listen method. At this point, both parties have a SendPort for sending messages to each other and a ReceivePort.listen for receiving messages.

4. Tests have shown that under default conditions, when multiple isolates access SQLite (each opening their own Database), read and write operations will be serialized. With proper planning at the app level, there is no problem.

--

--

Chencwf
Chencwf

Written by Chencwf

Focus on Flutter and AI Agents, love sharing programming knowledge