Now, let’s create an instance of the AsyncMemoizer class, and initialise it inside the initState method (or you can initialise during declaration).
Now, lets write the Future method.
(I will let you know why I gave the print statement)
So, we used the runOnce() method of the AsyncMemoizer instance to register an async method which will be run only once, even if we call the method multiple times !!
This way you can execute the future method inside the FutureBuilder without worrying about efficiency.
Proof 👇🏻
Now create a button which will trigger a setState. Notice the print statement. It gets executed only once (initially), even though the FutureBuilder is re-rendered again when you click the button!
This proves the async code is run only once in the entire lifetime of your screen.
This way we can avoid any complexities that could arise by using a variable approach.
For small applications, the variable approach won’t have much side-effects, but for production-level applications, this approach is preferred.
• • •
Missing some Tweet in this thread? You can try to
force a refresh
Every time your UI refreshes (eg: using a setState), the future method is run again, which can turn out to be very expensive!
Sometimes this could be helpful, but most of the times it’s a curse for the application.
So how can you fix it ?
👇🏻
We need to set the future in such a way that its run only once, and will never run again until you re-open the screen or you explicitly define a Swipe-down-to-refresh feature.
So, what is that one thing in Flutter, which will run only once in the entire life-cycle of your screen