Flutter 在导航到不同的路线后找不到正确的 Provider<Bloc>

Jon*_*vin 10 dart flutter flutter-provider flutter-bloc

我正在使用 bloc 来处理注册表单的状态。但我收到错误: Error: Could not find the correct Provider<CreateDidBloc> above this BlocBuilder<CreateDidBloc, CreateDidState> Widget
正如您在错误中看到的,我确实使用了块CreateDidBloc和状态CreateDidState,并通过 BlocBuilder 获取它们。
BlocBuilder 位于我的“注册”页面中,在我的例子中称为Creation。当我从介绍页面导航到创建页面时,会发生该错误。
下面是我的摘录,其中我用和MaterialApp包装了创建页面,以便创建页面可以访问 Bloc 和存储库。但由于某种原因,导航到创建页面后,页面找不到 BlocProvider 。RepositoryProviderBlocProvidercreationCreateDidBloc

initialRoute: "/introduction",
routes: {
  "/introduction": (context) => Introduction(),
  "/create": (context) => RepositoryProvider(
        create: (context) => CreateDidRepository(),
        child: BlocProvider(
          create: (BuildContext context) => CreateDidBloc(
            repo: context.read<CreateDidRepository>(),
          ),
          child: Creation(),
        ),
      ),
},
Run Code Online (Sandbox Code Playgroud)

这是我导航到屏幕的方式Creation

Navigator.push(context,
    PageTransition(type: PageTransitionType.fade, child: Creation()));
Run Code Online (Sandbox Code Playgroud)

创建(注册)页面:

@override
Widget build(BuildContext context) {
  return SafeArea(
      child: Scaffold(
          body: Column(
    children: [
      Expanded(
        child: PageView(
          physics: const NeverScrollableScrollPhysics(),
          controller: _pageController,
          onPageChanged: (index) {
            setState(() => currentStep = index);
          },
          children: [
            Step1(),
            Step2(),
            Step3(),
          ],
        ),
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          BlocBuilder<CreateDidBloc, CreateDidState>(
            builder: (context, state) {
              return ElevatedButton(
                  onPressed: () {
                    next();
                  },
                  child: Text(L.of(context).next));
            },
          ),
          BlocBuilder<CreateDidBloc, CreateDidState>(
            builder: (context, state) {
              return OutlinedButton(
                  onPressed:
                      state.formStatus is FormSubmitting ? null : cancel,
                  child: Text(L.of(context).back));
            },
          )
        ],
      ),
      const SizedBox(
        height: 16,
      )
    ],
  )));
}
Run Code Online (Sandbox Code Playgroud)

这是堆栈跟踪:

When the exception was thrown, this was the stack
#0      Provider._inheritedElementOf
#1      Provider.of
#2      ReadContext.read
#3      _BlocBuilderBaseState.initState
#4      StatefulElement._firstBuild
Run Code Online (Sandbox Code Playgroud)

Jon*_*vin 21

我找到了为什么我的 BlocBuilder 导航后找不到的原因CreateDidBloc。发生该错误的原因是,在 Flutter 中导航时会将页面推送到 widget 树中 MaterialApp 的正下方。这意味着我新导航的页面位于 BlocProvider 之上,该 BlocProvider 在 MaterialApp 下方的小部件树中指定。
为了解决这个问题,我只是用 MultiBlocProvider 和 RepositoryProvider 包装了我的 MaterialApp,这样无论我走哪条路线,都会在全球范围内提供 Bloc。
这是重要的摘录,我可以在其中全局定义块:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RepositoryProvider(
        create: (context) => CreateDidRepository(),
        child: MultiBlocProvider(
            providers: [
              BlocProvider<LanguageBloc>(
                  create: (context) =>
                      LanguageBloc(LanguagePreference.getLanguage())),
              BlocProvider<CreateDidBloc>(
                  create: (context) =>
                      CreateDidBloc(repo: context.read<CreateDidRepository>()))
            ],
            child: BlocBuilder<LanguageBloc, LanguageState>(
              builder: (context, state) {
                return MaterialApp(...)
Run Code Online (Sandbox Code Playgroud)

  • 创建全局提供程序是一种不好的做法,以防整个应用程序功能无法访问它们。您的注册块应仅提供给注册流程。 (9认同)