如何解决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: '/',)));
首先,在我的创建函数中,我用“_”覆盖了上下文,但我得到了同样的错误。 现在使用此代码段它可以完美运行,只需在我的提供者之前放置相同的上下文名称
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。