7

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

SardorbekR
  • 1,388
  • 3
  • 18
  • 33

2 Answers2

9

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...
}
SardorbekR
  • 1,388
  • 3
  • 18
  • 33
3

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

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
Abhishek Ghaskata
  • 1,802
  • 2
  • 6
  • 11
  • It can still be achieved without using a statefull widget. as it is adviced to avoid statefull widget as much as possible thus if the need for using a statefull widget is not there, leave it as stateless – Confidence Yobo Sep 20 '20 at 16:54
  • It didn't work, maybe because my BlocProvider wrapping MaterialApp. In my case BlocProvider is not wrapping BlocBuilder as in your example – SardorbekR Sep 21 '20 at 07:10
  • you mean like this.? ```BlocProvider( create: (_) => ProfileBloc(ProfileLoading()), // lazy: , child: Consumer( builder: (context, basemodel, _) { return MaterialAppWidget(); }, ), ),``` @SardorbekRkh – Abhishek Ghaskata Sep 21 '20 at 15:22
  • if yes then you can do like ```BlocProvider.of(context).add(ProfileInitialEvent());```. This also adds the initial event to the bloc where you want to use that bloc. Thanks. – Abhishek Ghaskata Sep 21 '20 at 15:25