Hello dev, sometimes when you are creating an app that requires some background execution you probably think about Future because you know that the code needs to do something and eventually gives you a response. But if this piece of code needs to do a heavy process and then gives you the response, well it might be a problem talking in the UI world because it may affect the user experience right? So… let’s talk about Isolates and try to solve this problem.
If you had never heard about Isolates I’ll give you a short explanation and also show an example but if are interested about it, after read this article I invite you to read the Dart documentation to deep understand.
In case you don’t know, your Dart program runs in a Isolates which means that your code is running in a processor inside a isolated box with its own scope, and if you try to run another Dart program you wont be able to exchange information between both right away, but you can do this with a few more steps.
You might be thinking, “why do I need such thing?” and my answer is… Imagine that your app needs to calculate a really heavy thing and when it finish eventually changes something on your UI, with Futures you will block this piece of code and the user will certain notice because he/she will not have the information and the UI will be kind of block.
In a practical and silly example imagine that you are talking to a person and this person is looking at the phone and not giving you attention, this is a Future case, and if this same person is playing with a pen and at the same time talking to you, this is a Isolate case, because this person can execute 2 things at the same time. Let’s se the example bellow.
In this example, notice when the app starts an Isolate is created and executed with a very simple code just to demonstrate the usability. But the thing here is, until the isolates executes the code the app keeps running with no problem. Off course you will not be coding anything like that using a Isolate but you can for example process an image or even a video download because these process are heavy to be computed in the main app Isolate.