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


This is my BlocProvider portion of code:

late BuildContext _context;
  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.


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

Answered By – reza

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *