It’s very hectic to manage state in flutter it when we have a complex UI and complex widget tree.
Before we jump into the state handling using bloc you need to understand about state management.
Why we need State management
Whenever we perform an operation on the widgets, suppose we have a RaiseButton and whenever we tap on it, it updates the Text, the very simple method is to use the
setState(). It is not a problem if you have a small widget tree but you need to avoid the
setState() if we have a complex Widget tree.
Why not setState()?
Suppose we have this Widget tree and we need to update only on development in the Widget tree but if we use setState(), it will rerender the whole widget tree and update all the elements.
There are few techniques for managing the state :
InheritedWidget: It allows you to pass the state to its child widgets, to youse the InheritedWidgets you need to add the Inherited widgets at the root of the widget tree but the problem with the InheritedWidget is that state is final when you are using theInhertedWidget so you cannot mutate the state.
Scoped Model: ScoperModel provides a better way to access, mutate and update widget state and it is built on top of InheritedWidget.
Model gets complex, it might be challenging to know when to properly call
notifyListeners() to avoid unnecessary updates.
let’s talk about Bloc
BLoC stands for Business Logic Component. Before we dive into bloc we need you to understand the Sink and Stream.
We add the data into the Sink and listen to the streams of data through Stream and updated the UI using StreamBuilder.
We will build a navigation drawer app and when we tap on the item on the drawer the screen replaces with another screen.
This is just like a Fragment Transaction in an Android app.
Step 1: Create a Bloc
We have created a class which contains a
StreamControllercontrols the stream of data and we have a
Streamwhich will be used in the
StreamBuilderto get the data flowing in the
Step 2: Create a Provider class
In this provider class, we have implemented our logic which is to update the current navigation value.
Step 3: Implement Provider class into Bloc
Now we have a bloc class which will update the navigation value and sink the value in the stream and uses it in
Step 4: Update the UI using StreamBuilder
So we have wrapped the body with StreamBuilder so whenever there is any change in the stream it will automatically update the body.
Add the drawer
Whenever we tap on any drawer item, first it will close the drawer menu using
Navigator.of(context).pop()then it updates the bloc which changes the navigation value and the data flows through the stream and
StreamBuilderupdates the UI.
Now its time to run the app.