4

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?

1 Answer 1

4

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

factory MyBloc.dispatch(() => MyBloc()..dispatch(MyEvent());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.