Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Flutter Performance Optimization

Ever wondered how flutter handles all your UI building and events like Futures, taps, etc.. on a single thread( yes it does all that on a single thread šŸ˜®šŸ˜®šŸ˜® until and unless explicitly done).

What is Thread/Isolates ?

Thread is an independent process that has its own chunk of memory and executes the given instructions on that memory , It can work parallelly with other threads hence can reduce execution time of multiple process on a single thread .

Letā€™s understand this with an exampleĀ :

In Fps games like counter strike, Call of duty, etc. you can see that as soon as you fire a weapon few tasks executes simultaneously like playing of bullet sound, change of bullet count and reduction in opponent health , All these things happens parallelly these are basically threads which execute parallelly and execute their task on separate isolates(isolates and threads can be used interchangeably as isolate is a Dart way of multi threading more on that below) which have its own memory.

Languages like JAVA and C++ Share Their heap memory with threads, but in case of flutter, every isolate has its own memory and works independently. As it has its own private space this memory doesnā€™t require locking, as if a thread finishes its task it already means that the thread has finished utilizing its memory space and then that memory can go for garbage collection.

To maintain these benefits flutter has a separate memory for every isolate(Flutter way of multi-threading) thatā€™s why they are called isolate šŸ™‚.

Learn more about isolates below.

How can it be helpful to me and where should I use isolates/Threads?

When to use isolates/threads ?

There are a few situations where isolates can be very handy.

  1. Let say you want to execute a network call and you want to process that data that you just receivedĀ . and that data contains about million records that alone will hang your UI.
  2. You have some image processing tasks that you want to do on-device these kinds of tasks are highly computational as they have to deal with lots of number crunching operations which may lead to frozen UI or legginess in UI.

So to conclude when to use isolates, We should use them whenever you think there is a lot of computation that needs to be offloaded from the main thread.

How to use isolates ?

Flutter team has designed a very elegant and abstract way of using isolates/threads in a flutter, Using compute we can do the same task which isolates does but in a more cleaner and abstract way. Letā€™s take a look at the flutter compute function.

Syntax:

var getData = await compute(function,parameter);

Compute function takes two parameters :

  1. A future or a function but that must be static (as in dart threads does not share memory so they are class level members not object level).
  2. Argument to pass into the function, To send multiple arguments you can pass it as a map(as it only supports single argument).

compute function returns a Future which if you want can store into a variable and can provide it into a future builder.

Letā€™s start by analyzing a sample problem:

/media/247dce48c8ac87e5b91b48cd11740086

In the above code pausefunction() is called just below the build method which pauses the execution of code for 10 seconds. And because of that when you try to navigate to this page from a previous one there will be a delay of ten seconds before our page gets pushed on to the widget tree.

We can try to resolve this issue by using async.

https://gist.github.com/702x/24a798189ac096e688f8301f0e2381f2#file-with10seconddelay-dart

As you can see now we have declared our pause function as async even doing this will not help

As async in dart is basically puts our code in ideal until there is something to compute so it seems to us that dart is executing these on a different thread but actually itā€™s just waiting for some event to occur in that async function.

More on async below :

https://gist.github.com/702x/b50dba38b3aae2e592bd26e2a94a1da5#file-with10seconddelayasync-dart

Letā€™s solve the above issue using compute.

In the above code, we basically passed our function in compute() function and that creates a separate isolate to handle the task and our main UI will still run without any delay (check the debug console for response ).

Summary:

  1. Dart is by default executes all its code on a single-threaded.
  2. Every function and every async-await calls work only on the main thread(until and unless specified).
  3. We can create multiple threads using compute( Future function/normal function, argument).
  4. You can use compute for executing network calls, performing number-crunching calculations, image processing, etc.

This is all about compute to learn more about isolates (the underlying architecture of computing function) check out isolate .

Thanks for reading this article.

If you find it interesting Please Clap! and if you found anything wrong please let me know I would appreciate it for your contribution.

Check out full code at FlutterDevs GitHub.


FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what youā€™re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Leave comment

Your email address will not be published. Required fields are marked with *.