Wamae Benson
2 min readJul 26, 2021

Async Vs Isolates in flutter

In flutter using async does not do the work in a background thread. Asynchronous operations let your program complete a task while waiting for another job to finish. Flutter does this through the event loop.

“Isolates are Dart’s model for multi-threading, though an isolate differs from a conventional thread in that it doesn’t share memory with the main program.” — dart.dev

Flutter uses isolates, isolates have their own event loop and memory, that is why they are called isolates.

To communicate between isolates you will have to implement sendPort and receivePort.

To create a simple isolate you can use Isolate.spawn or compute. Check the examples below:

void isolateFunction(int finalNum) {
int _count = 0;
for (int i = 0; i < finalNum; i++) {
_count++;
if ((_count % 100) == 0) {
print("isolate: " + _count.toString());
}
}
}
int computeFunction(int finalNum) {
int _count = 0;
for (int i = 0; i < finalNum; i++) {
_count++;
if ((_count % 100) == 0) {
print("compute: " + _count.toString());
}
}
return _count;
}

The functions have to live outside the class.

Isolate.spawn(isolateFunction, 1000);count = await compute(computeFunction, 2000);

The difference is that compute returns a value, allowing you to create complex logic e.g. use the output of one isolate as an input for another.

These my be useful for running long running tasks that may cause the UI to freeze e.g. parsing a large array of JSON objects.

Full example
https://github.com/tadaspetra/flutter_basics/tree/master/019_isolates?utm_source=pocket-app&utm_medium=share

Wamae Benson
Wamae Benson

Written by Wamae Benson

Project Manager | Software Engineer

No responses yet