👨‍💻 MultiThreading with Flutter Isolate

Mehmet Yozgatlı
Huawei Developers
Published in
2 min readOct 12, 2022

--

Image from CodeMagic

Introduction

Dart, despite being a single-threaded language, offers support for futures, streams, background work, and all the other things you need to write in a modern, asynchronous, and (in the case of Flutter) reactive way.

Flutter is great when it comes to UI and animation but what if your app freeze due to whatever reason such as

  • While calling heavy HTTP requests
  • Parsing huge JSON
  • database call
  • image decoding etc.

The foundations of Dart’s support for background work: isolates and event loops.

Event Loops

In Dart, it grabs an older event from its event queue, processes it, attends to the next event, and processes it until the events in the event queue are exhausted. Here’s an image that describes this process.

Source. An animation depicting how event loops work in Dart.

Isolates

An isolate is what all Dart code runs in. It’s like a little space on the machine with its own, private chunk of memory and a single thread running an event loop.

Many Dart apps run all their code in a single isolate, but you can have more than one if you need it. The new isolate gets its own event loop and its own memory, which the original isolate — even though it’s the parent of this new one — isn’t allowed to access. That’s the source of the name isolate: these little spaces are kept isolated from one another.

You can watch the visualization of Isolate in the video below.

There are two ways to create a different isolate in Dart: the Isolate.spawn() function and the compute() function.

Sample

Below you can see the usage of compute and spawn. Also, I tried to show you the time lost by making the thread wait using Await.

Sample Code about Isolate

Output

You can examine the outputs of Await, Compute and Spawn operations, respectively.

Output

Conclusion

When you use the concepts of Concurrency and Parallelism correctly while developing your application, you will prevent problems that may arise in both UI and background processes.

References

--

--