I am a beginner in Flutter and dart. I started learning bloc nowadays. When I get this code, I really didn't get it, how it works?
CounterBloc() : super(0) {
on<Increment>((event, emit) => emit(state 1));
}
- Is they calling super constructor?
- Defining it's constructor?
- why on keyword used?
- how second line works?
CodePudding user response:
Several things. First bloc is here to provide you with an abstract layer so it's not really important why it works but you should know how to use it.
However, here are answers to your questions:
- The
super
constructor is used (super(0)
) to set the initial state of your bloc - What you write is the definition of your bloc constructor yes, not sure what is the question here
on
is not a keyword. It's amethod
of thebloc
class. You can ctrl click on it to see how it's defined but it is not a dart keyword.- The second line basically registers the given callback (in your case
(event, emit) => emit(state 1)
) and maps it to an event type so that at a later date, when you use the event (myBloc.add(Increment())
) bloc will call the given callback.
I hope its clearer. Don't hesitate to dive into the bloc documentation as it is a precious resource (and is very pretty :D)