dart 在MultiBlocProvider中此BlocBuilder上方找不到正确的提供程序

j5fpnvbx  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(86)

在Flutter中,我使用了块,并且有一个特殊的情况,即MultiBlocProvider,我需要为它下面的小部件提供上下文。
这是代码:

@override
  Widget build(BuildContext **context**) {
    return MultiBlocProvider(
        providers: [
          BlocProvider<LoginCubit>(create: (_) => LoginCubit()),
          BlocProvider<UserDetailBloc>(
            create: (_) => UserDetailBloc(UserRepository())..add(UserLogged()),
          ),
        ],
        child: BlocBuilder(builder: (context, state) {
          return Scaffold(

字符串
问题是,我提供的背景下粗体,什么是错误的,有必要提供上下文下面MultiBlocProvider,但我不知道如何在代码中声明它.有一个例子如何做到这一点:

Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // we use `builder` to obtain a new `BuildContext` that has access to the provider
      builder: (context, child) {
        // No longer throws
        return Text(context.watch<Example>().toString());
      }
    );
  }


但我无法找到如何使用MultiBlocProvider声明它。

lx0bsm1f

lx0bsm1f1#

下面是使用MultiBlocProvider的更好方法的示例

MultiBlocProvider(
  providers: [
    BlocProvider<BlocA>(
      create: (BuildContext context) => BlocA(),
    ),
    BlocProvider<BlocB>(
      create: (BuildContext context) => BlocB(),
    ),
    BlocProvider<BlocC>(
      create: (BuildContext context) => BlocC(),
    ),
  ],
  child: ChildA(),
)

class ChildA extends StatelessWidget {
  ChildA({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold()
    )
  }
}

字符串

5sxhfpxr

5sxhfpxr2#

尝试像这样传递类型

BlocBuilder<BlocA, BlocAState>(
  builder: (context, state) {
  // return widget here based on BlocA's state
  }
)

字符串

示例对于您的情况,如果您希望LoginCubit在尖括号<>之间的BlockBuilder之后传递cubit & state。

// this
 child: BlocBuilder(builder: (context, state) {
          return Scaffold(

// should look like this
 child: BlocBuilder<LoginCubit, LoginState>(builder: (context, state) {
          return Scaffold(

相关问题