Flutter is single-threaded but it is capable of doing multi-threading stuff using Isolates (many processes).
When Dart starts, there will be one main Isolate(Thread). This is the main executing thread of the application, also referred to as the UI Thread.
In simple Flutter apps you will only ever use one Isolate, and your app will run smoothly.
Isolates are:
- Dart’s version of Threads.
- Do not share memory between each other.
- Uses Ports and Messages to communicate between them.
- May use another processor core if available.
- Runs code in parallel.
Isolates are good if you have a long-running task that you want to handle without hanging the user interface. Demonstrate using insulators in a small application.
We create a new flutter application
to demonstrate isolates in action, let's create a simple animation and also add a listener to our _animationController to make the animation loop.
in the widget tree we will animate the image loaded with assets. An AnimatedBuilder will repaint our picture, and the ScaleTransition will be responsible for increasing picture and necessary to free the animation from memory in the method dispose().
Now we will create a class Isolates in which we will use our animation and isolates
As calculations we will use the function Fibonacci, the method is based on a sequence of numbers. To use the method in another thread, it must be a global function.
by pressing the mainIsolateButton button, we will launch the Fibonacci method in the main thread and display the result in the snakBar
By pressing button secondIsolateButton we launch the fibonacci method in second thread. In this application we used compute() function. The compute() function runs expensive functions in a background isolate and returns the result. You can also use the Isolate.spawn() function to work with multithreading.
Now let's run our application
Video
Running the application, we constantly have animation working in the main stream and if we start the Fibonacci method in the same stream, we will see a delay of our user interface. When we process our method in another thread, we allocate new memory and even another kernel, due to which our user interface works smoothly.
If we test application performance, we will see the following numbers.
in main isolate - UI 7235.3 ms / frame, avg 66.0 ms / frame.
in second isolate we have - UI 28.9 ms / frame, avg 6.6 ms / frame.
There are several dependencies for working with multithreading:
flutter_isolate
isolate
isolate_executor
Official documentation about isolates:
https://api.flutter.dev/flutter/dart-isolate/Isolate-class.html
https://api.flutter.dev/flutter/foundation/compute.html