Hi Felix/bloc team,
Thank you for this awesome framework, which has standardized my whole flutter development experience !
I have one question which keeps coming back to me.
What is the proper way to fire an event right after widget is addded to widget tree.
Say I have a captcha widget, the initial state of it is to show a circular progress indicator.
Now what is the right way to trigger event, without user interaction, to start the actual loading process of captcha from the network.
class Bloc_Captcha extends Bloc<Event_Captcha, State_Captcha> {
Bloc_Captcha();
@override
State_Captcha get initialState => State_Captcha_loading();
@override
Stream<State_Captcha> mapEventToState(Event_Captcha event) async* {
if (event is Event_Captcha_reload) {
yield State_Captcha_loading();
//lets fetch the captcha from internet
var client = Client();
try {
var res = await client.get(event.url);
yield State_Captcha_loaded(res.body);
} catch (e) {
yield State_Captcha_failed();
}
}
}
}
Where exactly will I fire this event Event_Captcha_reload from, as it has to be done automatically without user pressing some button, right after this widget is added to the tree ?
Hi @anuragvohraec 馃憢
Thanks for opening an issue and for the positive feedback!
The easiest thing to do is fire the event from the create of BlocProvider
BlocProvider(
create: (context) => Bloc_Captcha()..add(Event_Captcha_reload()),
child: ...
),
Another option is you can create a StatefulWidget and in the State you can override initState and add the event there.
class _MyWidgetState extends State<MyWidget> {
@override
void initState() {
super.initState();
context.bloc<Bloc_Captcha>().add(Event_Captcha_reload());
}
}
Hope that helps 馃憤
Most helpful comment
Hi @anuragvohraec 馃憢
Thanks for opening an issue and for the positive feedback!
The easiest thing to do is fire the event from the
createofBlocProviderAnother option is you can create a
StatefulWidgetand in theStateyou can overrideinitStateand add the event there.Hope that helps 馃憤