1

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.

1 Answer 1

2

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));

3
  • Don'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.
    – noyruto88
    Feb 1, 2022 at 14:29
  • i 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?
    – reza
    Feb 1, 2022 at 14:36
  • Sorry, 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.
    – noyruto88
    Feb 1, 2022 at 14:47

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.