MultiRepositoryProvider不实例化Bloc

问题描述

我最近开始在Flutter中开发应用程序,因此我对该领域还很陌生。因此,我一直在研究使用Blocs。但是,当我实例化Bloc和我的服务时,一切正常。也就是说,直到我使用MultiRepositoryProvider我有2个代码段。第一个

return RepositoryProvider<AuthenticationService>(
      create: (context) {
        return FakeAuthenticationService();
      },// Injects the Authentication BLoC
      child: BlocProvider<AuthenticationBloc>(
        create: (context) {
          final authService = RepositoryProvider.of<AuthenticationService>(context);
          return AuthenticationBloc(authService)..add(AppLoaded());
        },child:  MaterialApp(
          title: 'Authentication Demo',theme: appTheme(),home: BlocBuilder<AuthenticationBloc,AuthenticationState>(
            builder: (context,state) {
              if (state is AuthenticationAuthenticated) {
                // show home page
                return HomePage(
                  user: state.user,);
              }
              // otherwise show login page
              return StartupPage();
            },),)
      ),);

代码可以正常工作,但是除了使用MultiRepositoryProvider之外的第二个代码段完全相同。第二个代码

return MultiRepositoryProvider(
      providers: [
        RepositoryProvider<AuthenticationService>(
          create: (context) => FakeAuthenticationService(),child: BlocProvider<AuthenticationBloc>(
            create: (context) {
              final authService = RepositoryProvider.of<AuthenticationService>(context);
              return AuthenticationBloc(authService)..add(AppLoaded());
            },)
      ],child: MaterialApp(
        title: 'Authentication Demo',AuthenticationState>(
          builder: (context,state) {
            if (state is AuthenticationAuthenticated) {
              // show home page
              return HomePage(
                user: state.user,);
            }
            // otherwise show login page
            return StartupPage();
          },);

现在第二个代码给我错误BlocProvider.of() called with a context that does not contain a Cubit of type AuthenticationBloc.

有人知道为什么第二个代码不起作用吗?

解决方法

我正在做同样的事情,但出现错误,但现在已解决

return MultiRepositoryProvider(
    providers: [
      RepositoryProvider<TranslationRepository>(
        create: (context) => TranslationRepository(),),RepositoryProvider<WeatherRepository>(
        create: (context) => WeatherRepository(),],child: MultiBlocProvider(
        providers: [
          BlocProvider<WeatherBloc>(
            create: (context) =>
                WeatherBloc(context.read<WeatherRepository>()),BlocProvider<ConnectivityBloc>(
            create: (context) => ConnectivityBloc(),BlocProvider<TranslationBloc>(
            create: (context) =>
                TranslationBloc(context.read<TranslationRepository>()),child: MaterialApp(
          title: 'Material App',onGenerateRoute: router.generateRoute,initialRoute: '/',)));

首先,在我的创建函数中,我用“_”覆盖了上下文,但我得到了同样的错误。 现在使用此代码段它可以完美运行,只需在我的提供者之前放置相同的上下文名称