If you are here for state management then I know your pain.
There are lot’s of problems with state management in flutter. Though flutter’s inbuilt method setState((){ /some code/ }) is great at keeping everything in 60 fps(Frame per second), it does not guarantee 60 fps if our app has complex ui and results in lag.
**But, **we can use BLOC pattern to save our app from lagging, even in slower phones too. Let’s see some details on BLOC pattern in flutter.
What is Bloc?
“A Bloc takes a stream of events as input and transform them into a stream of states as output.”
It is a design pattern which helps in separating the presentation layer from business logic.
Fig. 1 Typical Flutter Architecture
Many of us had used above architecture in their flutter project until we found any state management pattern like bloc or provider.
You request something and you get some response after some time. Right.
But wait. There’s a problem. Every time we asked for something we get something and then what we do is setstate((){});
And every time we did a setstate((){}); whole Widget Tree rebuilds again.
What does it mean. It means redrawing everything again.
And this is a** time consuming** as well as** memory consuming **process. If we are doing it on great extent then we are really killing flutter framework.
OK. We understood we need bloc pattern. But how to implement it in flutter?
Let’s see.
We will add one layer between presentation and backend in the above image (Fig. 1 Typical Flutter Architecture). And that is bloc.
It was bouncer isn’t it. Let’s see its implementation.
Fig. 2 BLoC Architecture
This time we will not call async Request/ Response methods directly, instead we will raise event and state.
Based on events we will trigger our logic and based on states we will update our UI.
**For eg. **If state is loading then app will show loading progress bar.If state is taskCompleted then app will show done animation. Like these, based on states app’s ui will change.
And guess what you** don’t have to use setState **in this case. Only ui related to current state will change, rest will be as it is. And this is how we can eliminate reloading of Widget Tree by avoiding setState. In result we are eliminate time consuming as well as memory consuming process that is **SetState((){}) **.
This is it for first part stay tuned for 2nd Part where we will **code in action **for Flutter’s BLoC.
Let me know if you find difficult to do this. I would love to solve your problems.
_Connect with me on: _GithubTwitterLinkedInInstagramYoutubePatreon
#flutter #setstate #tutorial #state-management #bloc