【发布时间】:2021-02-01 22:03:05
【问题描述】:
我最近开始在 Flutter 中开发一个应用程序,所以我对这个领域还很陌生。所以我一直在研究使用 Blocs。但是,当我实例化我的 Bloc 和我的服务时,一切正常。也就是说,直到我使用MultiRepositoryProvider。我有 2 个代码 sn-ps。第一个:
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();
},
),
)
),
);
这段代码工作正常,但第二个 sn-p 完全相同,除了它使用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',
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();
},
),
),
);
现在第二个代码给了我错误BlocProvider.of() called with a context that does not contain a Cubit of type AuthenticationBloc.
有谁知道为什么第二个代码不起作用?
【问题讨论】:
标签: flutter repository-pattern flutter-bloc