of<T extends BaseBloc> static method

T of<T extends BaseBloc>(
  1. BuildContext context, {
  2. bool listen = false,
})

A method that can be called by descendant Widgets to retrieve the bloc from the BlocProvider.

Important: When using this method, pass through complete type information or Flutter will be unable to find the correct bloc!

Example

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final bloc = BlocProvider.of<CounterBloc>(context);

    return StreamBuilder<int>(
      stream: bloc.counter,
      builder: (context, snapshot) {
        return Text(snapshot.data.toString());
      },
    );
  }
}

Implementation

static T of<T extends BaseBloc>(BuildContext context, {bool listen = false}) {
  try {
    return Provider.of<T>(context, listen: listen);
  } on ProviderError catch (e) {
    throw BlocProviderError(e.type);
  }
}