我正在使用 BLOC 模式对我的应用程序中的用户进行身份验证。我有一个主 BlocProvider 来包装我的应用程序。并根据身份验证状态构建一个 BlocBuilder。
如果用户未经身份验证,我有入门/介绍屏幕,将导航到登录屏幕。
登录屏幕包装在另一个 BlocProvider 中,其中包含一个用于登录的按钮,并在登录成功时添加登录事件。
问题是当我从入门屏幕导航时,我失去了主要的authenticationBloc上下文。在我推送新屏幕后,我需要做什么才能访问身份验证块。
void main() {
WidgetsFlutterBinding.ensureInitialized();
Bloc.observer = SimpleBlocObserver();
runApp(
MyApp(),
);
}
class AuthenticationWrapper extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BlocProvider<AuthenticationBloc>(
create: (context) => AuthenticationBloc()..add(AppStarted()),
child: MyApp(),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocListener<AuthenticationBloc, AuthenticationState>(
listener: (context, state) {
if (state is Authenticated) {
_appUserProfileRepository = AppUserProfileRepository();
}
},
child: BlocBuilder<AuthenticationBloc, AuthenticationState>(
builder: (context, state) { …Run Code Online (Sandbox Code Playgroud)