How to provide context to BlocProvider.of without using BlocBuilder in flutter bloc
680
remove late BuildContext _context;
and wrap your scaffold inside a Builder
widget. so the provided context is an updated context and you can simply use BlocProvider.of<AccountBloc>(context)..add(AddAccountEvent(account: account));
Author by
noyruto88
Updated on January 03, 2023Comments
-
noyruto88 over 1 year
This is my BlocProvider portion of code:
late BuildContext _context; @override Widget build(BuildContext context) { final _formKey = GlobalKey<FormState>(); return BlocProvider<AccountBloc>( create: (context) { _context = context; return AccountBloc(); }, child: Scaffold(
And inside the onPressed I use this.context:
BlocProvider.of<AccountBloc>(this._context)..add(AddAccountEvent(account: account));
When I run it the error says:
LateInitializationError: Field '_context@30149156' has not been initialized.
-
noyruto88 over 2 yearsDon't mind the _formKey sir, I used it in a form. Using a Builder will work. But it's the same as using BlocBuilder. Is there a way to use BlocProvider.of<Bloc>(context)..add(BlocEvent()) without using Builder or BlocBuilder? Thank you.
-
reza over 2 yearsi mean remove
late BuildContext _context;
sorry. you can move your scaffold in a separate widget. there is no way else. by the way, what is the problem with Builder? -
noyruto88 over 2 yearsSorry, I thought Builder is the same in BlocBuilder. The reason I don't want to use BlocBuilder because It's main use is when you want to access the state of a bloc.