Every one (almost) in Flutter world knows the Bloc state management library. But not everyone knows when (or how) to use it. So did I.
This article is only my vision of things, and may be more experienced developers will blow it to smithereens. May be it is wrong way to do things like I did. If so, please leave me a comment.
So, the Bloc. The main purpose I’m using it — is my intention to separate all logic from UI components (like views and other things). Besides, it was created for this (surprise surprise) if you didn’t know 🙂.
Let’s imagine that we have a web form like on the picture below:
This is one of the editor page of Operator18 CRM system. There are Textfields, DropdownLists and two separate inner forms to show list of messages and list of managers.
The logic of events I want to create is the following:
1. On the editor page initialization the main data will be passed to the Textfields and DropdownLists.
2. Then we need to load data for messages and managers lists, and this is where I’m using Bloc.
One of the Bloc’s condition is to provide the necessary Bloc before use it, otherwise you will get an error with text “Couldn’t find correct Provider<Type> above widget x”.
We can provide Bloc in two ways:
1. Place Provider above root MaterialApp widget. The MaterialApp has to be Provider’s child, as shown below:
2. Pass Provider in MatrerialPageRoute, right in the place where you navigate to another screen. You can do it like this:
At the end you will have access to the provided Blocs.
And now we can just create BlocBuilder for the list and declare states (for example) as follows:
It is now clear for me, that in places where your widgets have to load data first, you need to use Bloc. That’s my way to use it.
In Operator18 system there are places where I use Bloc for DropdownList, or for AlertDialog (alerts is another thing to handle when working with Bloc, because they have their own context, not linked with main widget’s context).
Thanks for reading!