简体   繁体   中英

Flutter BLoC BlocProvider.of() called with a context that does not contain a Bloc of type

Similar to this thread , so far no solution was relevant.

I get the following error:

BlocProvider.of() called with a context that does not contain a Bloc of type CategoryBloc.

The only widget:

class _TestWidgetState extends State<TestWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Test')),
      body: BlocProvider(
        builder: (context) => sl<CategoryBloc>(),   // dependency injection via GetIt
        child: Column(
          children: [
            BlocBuilder<CategoryBloc, CategoryState>(builder: (context, state) {
              if (state is Empty) {
                return Text('Empty');
              }
              if (state is Loading) {
                return Text('Loading');
              }
              if (state is Loaded) {
                return Text('Loaded');
              }
            }),
            RaisedButton(
              child: Text('Press me'),
              onPressed: () {
                dispatchAction(context);
              },
            ),
          ],
        ),
      ),
    );
  }

  void dispatchAction(BuildContext context) {
    BlocProvider.of<CategoryBloc>(context).dispatch(GetAllCategories());
  }
}

Dependency Injection via GetIt

 sl.registerFactory(() => CategoryBloc(getAllCategories: sl()));
...

For completeness I will provide all the bloc files

CategoryBloc

class CategoryBloc extends Bloc<CategoryEvent, CategoryState> {
  final GetAllCategoriesUsecase getAllCategories;

  CategoryBloc({@required this.getAllCategories})
      : assert(getAllCategories != null);

  @override
  CategoryState get initialState => Empty();

  @override
  Stream<CategoryState> mapEventToState(CategoryEvent event) async* {
    if (event is GetAllCategories) {
      yield Loading();
      final failureOrCategories =
          await getAllCategories(Params(limit: 10, skip: 0));
      yield failureOrCategories.fold(
          (failure) => Error(error: _mapFailureToMessage(failure)),
          (categories) => Loaded(list: categories));
    }
  }

  String _mapFailureToMessage(Failure failure) {
    ...
  }
}

CategoryEvent

@immutable
abstract class CategoryEvent extends Equatable {
  CategoryEvent([List props = const <dynamic>[]]) : super();
}

class GetAllCategories extends CategoryEvent {
  @override
  List<Object> get props => [];
}

CategoryState

@immutable
abstract class CategoryState extends Equatable {
  CategoryState([List props = const <dynamic>[]]) : super();
  @override
  List<Object> get props => [];
}

class Empty extends CategoryState {}

class Loading extends CategoryState {}

class Loaded extends CategoryState {
  final List<Category> list;

  Loaded({@required this.list});

  @override
  List<Object> get props => [list];
}

class Error extends CategoryState {
  final String error;

  Error({@required this.error});
  @override
  List<Object> get props => [error];
}

pubspec.yaml

  get_it: ^3.0.1
  flutter_bloc: ^0.21.0   # old version :(
  equatable: ^1.0.1

So far I have tried:

  • specifying the type body: BlocProvider<CategoryBloc>( - same error

Any help is greately appeciated.

Found the answer after hours of google searches.

Flutter_bloc requires the BlocProvider and BlocBuilder to be in separate widgets , such that the Bloc Builder's context is hierarchically 'under' the one for Builder.

class _TestWidgetState extends State<TestWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Test')),
      body: BlocProvider<CategoryBloc>(
        builder: (context) => sl<CategoryBloc>(), //
        child: TestWidget2(),
      ),
    );
  }
}

class TestWidget2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        BlocBuilder<CategoryBloc, CategoryState>(builder: (context, state) {
          if (state is Empty) {
            return Text('Empty');
          }
          if (state is Loading) {
            return Text('Loading');
          }
          if (state is Loaded) {
            return Text('Loaded');
          }
        }),
        RaisedButton(
          child: Text('Press me'),
          onPressed: () {
            dispatchAction(context);
          },
        ),
      ],
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM