Isolates in Flutter | Dart Isolate Tutorial — Run tasks in background using Isolates
In this article we will discuss about when, why and how to use isolates in Flutter apps.
🎥 Video Tutorial
🔭 Implementation
Just like threads what we have in java, we have isolates here in flutter. Each isolate has its own memory where it performs the event looping. So in general isolates are individual worker components that can do the given task without affecting the main dart engine. Since dart language is single threaded, isolates can be used for achieving multi-threading in flutter apps.
So this is what isolate technically is.
Now let’s turn our attention towards the question,
Why do we need to use isolates in our flutter app?
Lets try to answer this question with the help of a simple example. Consider we the basic UI containing a circularProgressIndicator
and Elevated button
widgets placed at the center of our app screen as shown below👇.
Scaffold(
appBar: AppBar(title: const Text('Isolates')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 50),
ElevatedButton(
child: const Text('Run Heavy Task'),
onPressed: () => runHeavyTaskWithOutIsolate(4000000000),
),
],
),
),
);
In the above code snippet, we try to call runHeavyTaskWithOutIsolate()
method which by it’s name is going to perform a heavy duty task without using isolate (it can be file operation, network related work etc.,) which depends on our use-case.
In this article, to keep it simple we will make use of basic for loop
that will iterate for 4000000000
(which is passed as a parameter).
The runHeavyTaskWithOutIsolate()
method is as follows.,
int runHeavyTaskWithOutIsolate(int count) {
int value = 0;
for (var i = 0; i < count; i++) {
value += i;
}
print(value);
return value;
}
Now if we run our app, we will notice that upon clicking the button (which calls the runHeavyTaskWithOutIsolate()
method) the circularProgressIndicator
widget that was loading infinitely, gets stuck and freezes until the for
loop completes it’s execution.
This clearly says us that, since dart is single threaded language, the main thread is busy executing the 4000000000
(4 billion) iterations. so it has no time to refresh the UI components. Once the heavy task (4 billion) iteration is complete, the main thread or the main isolate turns its focus to the UI thereby refreshing back to its original state where we will be able to observe the circularProgressIndicator
getting loaded back again.
So this is a typical example, where the isolate needs to be used. Hence now let’s try using isolate for performing the same heavy task and see if our circularProgressIndicator
is getting stuck at any point of time. Therefore our previous code needs to be updated as follows.,
Scaffold(
appBar: AppBar(title: const Text('Isolates')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 50),
ElevatedButton(
child: const Text('Run Heavy Task'),
onPressed: () => useIsolate(),
),
],
),
),
);
The useIsolate()
methods which is called inside the onpress
event is as follows,
useIsolate() async {
final ReceivePort receivePort = ReceivePort();
try {
await Isolate.spawn(
runHeavyTaskIWithIsolate, [receivePort.sendPort, 4000000000]);
} on Object {
debugPrint('Isolate Failed');
receivePort.close();
}
final response = await receivePort.first;
print('Result: $response');
}
int runHeavyTaskIWithIsolate(List<dynamic> args) {
SendPort resultPort = args[0];
int value = 0;
for (var i = 0; i < args[1]; i++) {
value += i;
}
I
Here in the above code we have made use of isolates
to perform the same task. Wherein we use the Isolate.spawn()
method and pass in the function that is going to perform the heavy task followed by the arguments if any.
Additionally, we make use of the PORTS
(Send
and receive
ports) to pass the data between isolates.
Now if we run our app, we will notice that the CircularProgressIndicator
widget that was getting freezed earlier won’t get affected now. Because we have now added the isolate to perform the heavy task, so it can run independently to do the computation without affecting the main dart thread.
Well that’s it. 🎉 Run the code to see it in action.🥳
Refer my video tutorial for complete guide:👉 https://www.youtube.com/watch?v=g6sPAWCFgtE
Get the complete source code here:👉 https://github.com/vijayinyoutube/isolates_demo
Check out all my Flutter related blogs here.,👇
Other articles you may like.,
🔵Setting up your Flutter app for publishing in Play Store.
🔴Confetti Animation in Flutter
🟡 Change App Launcher Icon in Flutter
🔴 AnimatedContainer Widget in Flutter
Most popular
Flutter Tutorials
If you found this article useful and wish to support my work, you can consider buying me a ☕️ coffee.👇
If you want to know more about Flutter and various Widgets in Flutter…?🤓 Then visit my channel 👉🏻 vijaycreations🚩
Thanks.,