What is "flutter" bloc?
Flutter bloc is one of the state management for Flutter applications. You can use it to handle all the possible states of your application in an easy way.
Flutter bloc is simple to use because you and your team are going to understand the concept quickly, no matter what is your level, this library has very good documentation with tons of examples and also, is one of the most used in the flutter community, so if you have any question or problem you probably are going to find the solution with a simple search on the internet.
Is powerful because is going to help you to create all kinds of applications, you can create applications for learning purposes for example, and also you can create complex applications in a production environment and flutter bloc is valid in both cases.
Another important aspect of this library is that you could test your bloc logic in an easy way.
So… How can I start with Flutter bloc?
My first suggestion for you is that you should go through the documentation and read the basics, here in this article I’m going to try to explain it, but if you need to go more deeply I highly recommend you to visit the docs.
How does it work?
When you use flutter bloc you are going to create events to trigger the interactions with the app and then the bloc in charge is going to emit the requested data with a state, in a real example it will be like that:
1- User click on a button to get a list of games.
2- The event is triggered and it informed to bloc that the user wants a list of games.
3- The bloc is going to request this data ( from a repository for example, which is in charge of connecting to the API to get the data).
4- When the bloc has the data it will determine if the data is Success or is Error, and then it's going to emit a state.
5- The view is going to be listening to all the possible states that the bloc could emit to react them. For instance, if bloc emits Success as a state the view is going to rebuild it with a list of games, but if the state is Error the view is going to rebuild with an error message or whatever you want to show.
Perfect, now you know the main concept of how flutter bloc works! Now, it’s time to know how you can use it.
Imagine that you want to create a bloc logic related to games, you are going to need these three classes:
games_bloc.dart
games_state.dart
games_event.dart
As you can see you are going to need a bloc, state, and event class. Inside each class, you are going to manage the needed information, don’t worry we are going to see them very soon, but now I want to explain to you the basic concepts about de bloc widgets.
Bloc Widgets
These are widgets that the library provides you to manage all the possible cases, for example, add an event, listen to a state, emit a state, rebuild the view depending on the state, and so on.
BlocProvider/MultiBlocProvider
BlocProvider is in charge of providing a bloc to its children. Is the way of “initializing” the bloc before using it.