Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FLutter - How to dispatch an event on BLoC initialization

I know how you can set the initial state of a bloc easily. Is it possible to dispatch an event when a new bloc is created?

class MyBloc extends Bloc<MyEvent, MyState> {
  MyBloc() :
    this.dispatch(MyEvent()), // this line doesn't work
    super();

  @override
  MyState get initialState => MyStateInitial();

  @override
  Stream<MyState> mapEventToState(MyEvent event) async* {
    if (event is MyEvent) {
      ... do some stuff here ...
      yield MyStateAfterMyEvent(someParameters, thatCantBe, setManually);
    }
  }
}

I know passing parameters to the bloc constructor could work sometimes. In my case parameters are fetched from the internet so I need more dynamic option. What is the way of achieving this?

like image 287
prkmk Avatar asked Oct 22 '25 17:10

prkmk


1 Answers

You can do it with the cascade operator .. and a ' factory constructor.

factory MyBloc.dispatch(() => MyBloc()..dispatch(MyEvent());
like image 197
Sergio Bernal Avatar answered Oct 25 '25 06:10

Sergio Bernal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!