I have 10 buttons in main menu of my app and each of them contains BlocBuilder inside them.

So when I click on those buttons to open a new page, I want to dispatch the first event, but I don't know how. I can change all classes to stateful widget and then call bloc.dispatch(event) inside initialState() function, but I would like to discover another way, and not sure whether it's the best way


Solution 1: Abhishek Ghaskata

you can use .. operator to add event while declaring like

BlocProvider(
            create: (context) => FirstBloc()..add(InitialiEvent()), // <-- first event, 
            child: BlocBuilder<FirstBloc, FirstState>(
              builder: (BuildContext context, state) {
                ...
              },
            ),

or you can do it inside the initState method as well


Solution 2: SardorbekR

In order to trigger the first event/method call inside BlocBuilder I had to add bloc argument and give parameter provided my BlocProvider, only after this I managed to call my method.

BlocBuilder<MyCubit, MyState>(
      bloc: BlocProvider.of<MyCubit>(context)..myFunction(),
      builder: (BuildContext context, state) {
//Your code...
}