Search code examples
flutterdartblocflutter-bloc

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:

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