使用不包含 StateStreamableSource 的上下文调用 BlocProvider.of() <Object?>

问题描述 投票:0回答:1

我正在尝试使用 Cubits 来管理仅特定屏幕(配置文件屏幕)的状态

我已经提供了我的块并消耗了它,但是发生了意外的异常:

       BlocProvider.of() called with a context that does not contain a StateStreamableSource<Object?>.

众所周知,消费者开始在小部件树的更高级别中搜索区块提供者(它位于消费者正上方)。

这是屏幕

  Widget build(BuildContext context) {
    return BlocProvider(
        create:(context)=>ProfileScreenCubit(),
        child: BlocConsumer<ProfileScreenCubit,ProfileScreenStates>(
        listener: (context,state){},
        builder: (context,state){
      
          var cubit = ProfileScreenCubit.getCubit(context); // exception here

          return Scaffold(...);
        },
      ),
    );
  }

这是肘

final class ProfileScreenCubit extends Cubit<ProfileScreenStates>{

  ProfileScreenCubit():super(ProfileScreenInitialState());

  static getCubit(BuildContext context)=>BlocProvider.of(context);


}

实际上,还有其他屏幕也是以这种方式管理的。很奇怪!

感谢您的帮助,谢谢。

flutter dart mobile bloc
1个回答
0
投票

好的,明白了。

我回来了

dynamic

static getCubit(BuildContext context)=>BlocProvider.of(context);

此外,我将我的

cubit
定义为
var

  var cubit = ProfileScreenCubit.getCubit(context); // exception here

这取决于 dart 分析器来推断类型(始终是

dynamic
)。

因此,它不是可流式源。

修复

  static ProfileScreenCubit getCubit(BuildContext context)=>BlocProvider.of(context);

添加类型

ProfileScreenCubit

的返回数据类型
© www.soinside.com 2019 - 2024. All rights reserved.