Single Thread Dart, What? — Part 1

Dave Parth
Globant
Published in
4 min readJan 7, 2020

I know some of you might come to me and say there is Async Await and RxDart so don’t need to worry bro. and I was totally into it but after reading a lot of why application performance is mandatory in Flutter I came to know that Dart is a Single Threaded framework.

Dart is a single-threaded system. Sometimes we have hard times using this as now every language is using a multi-threaded system and dart uses old concepts but it’s not over yet and Dart is still evolving. The main reason to take this point is to start the Flutter Isolates but let’s first check why we need to have Isolate.

IMPORTANT Dart executes one operation at a time, one after the other meaning that as long as one operation is executing, it cannot be interrupted by any other Dart code.

Create a default new flutter app that will create an increment counter template.

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}

We have added circularProgressIndicator just to check when the UI stucks or skips frame. Let’s update incrementCounter function.

void _incrementCounter() {
setState(() {
var string = Constants.str;
for(int index = 0;index <10;index++) {
for (int i = 0; i < string.length; i++) {
string += string[i];
}
}
_counter++;
});
}

Click on the FAB button, the circular progress bar stuck for a while and loads again. This is due to heavy lifting on the main thread(or I can say the Main isolate, Yah’s main thread is here in flutter is Main Isolate). Well, you will probably say “Ahhh!! It’s easy, just put this code in an async function and call it from there” Well that is correct but it’s not going to work. Why? because Dart works on event-loop mechanism what it means is it creates events for the main thread or any isolate and runs the event priority basis.

Event loop

The event loop is kind of like an infinite queue or loop, which runs forever. Example: create an async function and call it. at the point of time what Event loop contains is this sequence of information.

  1. return an output of the method i.e. Future
  2. run async function synchronously up to the first await keyword.
  3. wait for that async function to finish and execute the remaining code.

An async method is NOT executed in parallel but following the regular sequence of events, handled by the Event Loop, too.

so if we have

main(){
method1();
method2();
}
method1() async{
print("1");
}
method2() async{
Future((){
print("Future 2");
});
print("2");
}

output:

1
2
Future 2

So in the main isolate what event loop contains is like this

  1. call method1
  2. call method 2
  3. Add Future event from method 2
  4. execute a print statement
  5. execute future event from method 2

Why Future from method 2 not run before print 2? because every entry point goes inside the event loop and as the futures will not be needed at that point of time the next sequence will get executed before futures. If we tweak code a little bit it will show a different result.

method2() async{
await Future((){
print("Future 2");
});
print("2");
}

Now it will print

1
Future 2
2

As the event loop come to know that it needs to await for the result before executing the next statement.

After executing the main method every change has to go through the event loop to update the data. and so you might feel lag in UI when building the Flutter app due to this. Like doing IO operation or bitmap manipulation is kind of CPU or Disk process and it takes a lot of time inside the event loop so the next frame will not get updated and UI will be stuck for a while. Check --profile flag for more details to check the profile tooling in flutter(Will cover how to check this later in the post).

Reference Links:

  1. Isolate and event loop intro video from Flutter Devs

TLDR;

Flutter uses dart and dart uses event loop so flutter is also a single-threaded system. This is why we must avoid some intensive work on main-thread like write to file or fetching data and operating large compute operations.

Continue reading Part 2 from below.

Do you know you can press the clap👏 button 50 times? The higher you go, the more it motivates me to write more stuff for you guys!

Hello, I am Parth Dave. A noob developer and noob photographer. You can find me on Linkedin or stalk me on GitHub or maybe follow me on Twitter?

Have a nice fluttery day!

--

--

Dave Parth
Globant
Writer for

Developer, Photographer. Flutter and Automation enthusiast.