Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatch first bloc event or cubit method, on page start inside StatelessWidget

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

like image 971
SardorbekR Avatar asked Jan 25 '23 17:01

SardorbekR


2 Answers

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...
}
like image 164
SardorbekR Avatar answered May 12 '23 12:05

SardorbekR


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

like image 34
Abhishek Ghaskata Avatar answered May 12 '23 12:05

Abhishek Ghaskata