Home > database >  New bloc pattern - How it works?
New bloc pattern - How it works?

Time:10-04

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));
  }

  1. Is they calling super constructor?
  2. Defining it's constructor?
  3. why on keyword used?
  4. 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:

  1. The super constructor is used (super(0)) to set the initial state of your bloc
  2. What you write is the definition of your bloc constructor yes, not sure what is the question here
  3. on is not a keyword. It's a method of the bloc class. You can ctrl click on it to see how it's defined but it is not a dart keyword.
  4. 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)

  • Related