The Dart programming language allows programmers to write code that executes asynchronously. This allows Dart 2.4.0 (and also Flutter) to do things like execute HTTP requests, and patiently wait for a response before continuing to execute the proceeding code.
Dart also allows a programmer to execute a function asynchronously in a separate thread! This can be done using the Isolate class, which is in a native Dart library. A Dart Isolate is an object that executes a specific function in a newly spawned thread. The second thread can communicate with the main thread continuously.
Async Dart Isolates
The Isolate class was designed for message passing between threads using a non-broadcast streaming object called a ReceivePort. What this means is a ReceivePort can be listened to just once. A contrasting method in the ReceivePort object is called the SendPort.
ReceivePorts are for listening for messages, and SendPorts are for sending messages.
Dart Thread Code Example
In order to make async threads with Isolates, you need import 2 native Dart libraries. No need to install them, they come with Dart.
Next we’ll create a function that initializes our Isolate. The function listens for messages that the Isolate sends to the main thread. Lastly, the function returns a SendPort, so the main thread can send data to the Isolate whenever it wants.
Next we will make the function that our Isolate object will execute in a new thread. We pass a reference to this function to the Isolate object’s spawn method, along with a SendPort. The SendPort is passed so the new thread can send messages to the main thread.
This enables continuous, two-way communication between the Dart/Flutter main and Isolate threads.
Next we will create the main function. This makes our Dart program set up a second thread with two-way message passing ability.
Let’s put the whole program together, and add an exit call, so the program doesn’t infinitely hang.
You will see in your system output that the print functions spit out messages passed from main to Isolate, and vice versa.
$ dart isolate-example.dart
[isolateToMainStream] This is from myIsolate()
[mainToIsolateStream] This is from main()
Now you can make multiple Dart threads and pass messages between them using streams!