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

2

8

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

Selves answered 20/9, 2020 at 16:27 Comment(1)
Pls, show your code so we can know where to start fromMasry
S
10

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...
}
Selves answered 30/9, 2020 at 7:30 Comment(2)
But first state is missing in blocListenerPrescription
For me I had to add the bloc argument.Argumentative
A
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

Annuity answered 20/9, 2020 at 16:50 Comment(4)
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 statelessMasry
It didn't work, maybe because my BlocProvider wrapping MaterialApp. In my case BlocProvider is not wrapping BlocBuilder as in your exampleSelves
you mean like this.? BlocProvider( create: (_) => ProfileBloc(ProfileLoading()), // lazy: , child: Consumer<BaseModel>( builder: (context, basemodel, _) { return MaterialAppWidget(); }, ), ), @SardorbekRkhAnnuity
if yes then you can do like BlocProvider.of<ProfileBloc>(context).add(ProfileInitialEvent());. This also adds the initial event to the bloc where you want to use that bloc. Thanks.Annuity

© 2022 - 2024 — McMap. All rights reserved.