In this blog, I explain about Future class and it’s feature or functionality with code example.
Generally, beginners confused, what is
Future, class how to use it, where we can use it, etc. So don’t skip any single line in this blog for a better understanding of the topic.
Before starting the code first learn what is Future class
A future is used to perform asynchronous tasks in flutter it is defined exactly like a function in the dart, but instead of the void, you use Future. If you want to return a calculated value from the Future then you pass a
<data-type>. The future can have a return type as a function return type as you need.
Future performs an asynchronous task using Future, Async, Await and Then keyword.
If you used asynchronous tasks before so maybe you have remembered that we have to use asynchronous tasks only that condition when we have need to perform a long task. For example:-
Start printed the getState() is called. Since getState() is Future type and a then() is attached to it. The program does not wait for getState() data and proceed further prints END.
As we can see that the return value of the getState() has
then()which execute when Future function receives a data returned i.e
data value is You are learning Future.
async makes it execute parallel and occurs after 2 secs delay as
await wait for data to return and then proceed further. That’s why program didn’t wait for 5 secs delay code and printed
A 5 sec Delay later and in parallel.
wait for a Future function to return data and then proceeds to next line, mostly you will use
then()when you don’t have to wait for data, the logic for that data is in
then() , while, in await programs wait for data to
returnand assign the value to variable that will be on left of
In some exception you might use
thentogether, that depends on your logic.
Future and sync are used for background processing i.e non-ui thread , for let’s say using REST API, decoding-encoding, Android and iOS Native calls, SQLite storage etc.
If you have some doubt you can ask and comment below.