Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to provide context to BlocProvider.of without using BlocBuilder in flutter bloc

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

LateInitializationError: Field '_context@30149156' has not been initialized.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading