Isolates

Isolate is something where all Dart program runs. It has a piece of memory and runs a single thread. In a programming language like Java, developers can create multiple threads and share the same memory. Dart allows us to create multiple Isolates what is similar to multithreading, but it’s not.

Isolates are used to do the heavy computation to avoid the slowdown of the main program.

Isolates have one limitation — sharing memory between two isolates is not possible. Despite that, Isolates able so send messages to each other. Such functionality compensates lack of multithreading.

Here is a full example of how to spawn(create) Isolate and establish communication between the main thread and isolate thread.

Inside createNewIsolate method new Isolate creates using static method of Isolate class — Isolate.spawn. Static method Isolate.spawn accept two parameters:

callback what executes when Isolates instantiates— isolateMain.

an instance of SendPort class.

An instance of ReceivePort class has an instance of SendPort class — receivePort.sendPort.

ReceivePort and SendPort are the main classes to send and receive messages from one side to another. isolateMain function receives that instance of SendPort. Then use timer and sendPort parameter to send multiple messages to the primary Isolate.

receivePort.sendPort == sendPort

receivePort — listens to new incoming messages

sendPort — send new messages from one Isolate to another Isolate.

That’s how communication between Isolates works. Use this powerful feature to do some heavy computation to keep the app fast and responsive.