4

错误:I/flutter(5919):══╡ 小部件库发现异常╞═════════════════════════␕════════════ ═══════════════════════════ I/flutter(5919):在构建构建器时抛出了以下断言:I/flutter(5919):BlocProvider .of() 使用不包含 Bloc 类型的 Bloc 的上下文调用。I/flutter (5919):从传递给 I/flutter (5919) 的上下文开始找不到祖先:BlocProvider.of>()。我/颤振(5919):
如果您使用的上下文来自 BlocProvider 上方的小部件,则可能会发生这种情况。I/flutter (5919): 使用的上下文是: BlocBuilder, dynamic>(dirty, state: I/flutter (5919): _BlocBuilderBaseState, dynamic>#55a7d(lifecycle state: created)) I/flutter (5919): 相关导致错误的小部件是:I/flutter(5919):MaterialApp /lib/main.dart:35:12

这是我的主要内容

void main() {
  final StorageRepository storageRepository = StorageRepository();
  final AuthenticationRepository authenticationRepository =
      AuthenticationRepository();
  runApp(BlocProvider<AuthenticationBloc>(
      create: (_) => AuthenticationBloc(
          authenticationRepository: authenticationRepository,
          storageRepository: storageRepository),
      child: MyApp()));
}

MaterialApp 小部件

MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.deepPurple),
      home: BlocBuilder(
        builder: (context, state) {
          print(state);
          if (state is Authenticated) {
            return MainPage();
          } else if (state is Unauthenticated) {
            return LoginPage();
          } else if (state is Uninitialized) {
            return SplashScreen();
          }

          return Container();
        },
      ),
4

2 回答 2

4

您忘记将 Bloc 和 State 类型赋予 BlocBuilder 小部件

MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.deepPurple),
      /// You need to specify the type here, 
      /// that's why you got error Bloc<dynamic, dynamic>
      home: BlocBuilder<AuthenticationBloc, AuthenticationState>(
        builder: (context, state) {
          print(state);
          if (state is Authenticated) {
            return MainPage();
          } else if (state is Unauthenticated) {
            return LoginPage();
          } else if (state is Uninitialized) {
            return SplashScreen();
          }

          return Container();
        },
      ),
于 2020-02-04T07:59:25.373 回答
0

由于错误,本身建议BlocProvider不访问context使用该集团的权利

MultiBlocProvider提供添加多个提供者的能力,然后这些提供者可以在MultiBlocProviderBlocProvider列表转换为嵌套 BlocProvider小部件树时获得正确的上下文访问。

MultiBlocProvider(
          providers: [
            BlocProvider<YourBloc>(
                create: (BuildContext context) =>)
          ],
          child: MaterialApp(
            home: BlocBuilder<YourBloc, YourState>(
于 2021-06-16T10:59:53.970 回答