简体   繁体   English

Flutter 使用不包含 Bloc 类型的上下文调用的 BLoC BlocProvider.of()

[英]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通过 GetIt 进行依赖注入

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

For completeness I will provide all the bloc files为了完整起见,我将提供所有的 bloc 文件

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 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指定类型body: BlocProvider<CategoryBloc>( - 同样的错误

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. Flutter_bloc 要求BlocProviderBlocBuilder位于单独的小部件中,这样 Bloc Builder 的上下文在层次上位于 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);
          },
        ),
      ],
    );
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter:使用不包含 Bloc 类型的上下文调用 blocprovider.of() - Flutter: blocprovider.of() called with a context that does not contain a Bloc of type 使用不包含 Bloc 类型的上下文调用 Flutter BlocProvider.of() - Flutter BlocProvider.of() called with a context that does not contain a Bloc of type Flutter Bloc Cubit Navigator Problem BlocProvider.of() 调用的上下文不包含 CityCubit 类型的 Bloc/Cubit - Flutter Bloc Cubit Navigator Problem BlocProvider.of() called with a context that does not contain a Bloc/Cubit of type CityCubit Flutter / BLoC - BlocProvider.of() 调用的上下文不包含 ArticlesBloc 类型的 Bloc - Flutter / BLoC - BlocProvider.of() called with a context that does not contain a Bloc of type ArticlesBloc BlocProvider.of() 使用不包含 TrackingBloc 类型的 Bloc 的上下文调用 - BlocProvider.of() called with a context that does not contain a Bloc of type TrackingBloc 使用不包含 FicheMvtBloc 类型的 Bloc 的上下文调用 BlocProvider.of() - BlocProvider.of() called with a context that does not contain a Bloc of type FicheMvtBloc BlocProvider.of() 使用不包含 OfflineBloc 类型的 Bloc 的上下文调用 - BlocProvider.of() called with a context that does not contain a Bloc of type OfflineBloc BlocProvider.of() 调用的上下文不包含 WeatherBloc 类型的 Bloc/Cubit - BlocProvider.of() called with a context that does not contain a Bloc/Cubit of type WeatherBloc 使用不包含 Bloc 类型的上下文调用 BlocProvider.of() - BlocProvider.of() called with a context that does not contain a Bloc of type BlocProvider.of() 使用不包含 CLASS 类型的 Bloc 的上下文调用 - BlocProvider.of() called with a context that does not contain a Bloc of type CLASS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM