Flutter Bloc:在使用Navigator + Bloc时从任何地方注销



我是新手,尝试使用Bloc来解决导航部分。

我想可能添加到日志从应用程序中任何地方。

细节:

我正在研究Notes应用程序(只是为了学习),并且已经用BlocProvider包装了MaterialApp,所以我可以从任何地方访问AuthBloc。MaterialApp 'home'小部件是主页,它返回BlocConsumer,因此它可以根据事件返回状态。因此,如果用户已经登录-我发出AuthStateLoggedIn并返回ViewNotePage。从ViewNotePage(通过点击一个具体的笔记)我去NotePage,使用MaterialPageRoute。如果我从NotesListPage发出AuthEventLogOut(通过按下LogOut按钮)-什么都不会发生,直到我调用Navigator.of(context). popuntil (ModalRoute.withName('/'))。下面是代码

void main() {
runApp(const MyApp());
}
// App
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider<AuthBloc>(
create: (context) => AuthBloc(FirebaseAuthProvider()),
child: MaterialApp(
title: 'Notes',
theme: Colors.blue,
home: const HomePage(),
routes: {
viewNotePage: (context) => const ViewNotePage(),
}
),
);
}
}

首页//

class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
context
.read<AuthBloc>()
.add(const AuthEventInitialize());
return BlocConsumer<AuthBloc, AuthState>(
listener: (context, state) {
if (state.isLoading) {
// loading is handled here
}
},
builder: (context, state) {
if (state is AuthStateLoggedOut) {
return const LoginView();
} else if (state is AuthStateRegistering) {
return const RegisterView();
} else if (state is AuthStateNeedsVerification) {
return const VerifyEmailView();
} else if (state is AuthStateLoggedIn) {
return const NotesPage();
} else if (state is AuthStateForgotPassword) {
return const ForgotPasswordView();
}
return const Scaffold(body: CircularProgressIndicator());
},
);
}
}

//NotesPage

为了缩短代码,我基本上可以这样做:

await Navigator.of(context).pushNamed(viewNotePage, arguments: someArgs);

//ViewNotePage

context.read<AuthBloc>().add(const AuthEventLogOut());
Navigator.of(context).popUntil(ModalRoute.withName('/'));  // without popUntil - I stay on the ViewNotePage

所以从我的理解,当我使用MaterialPageRoute -它创建一个新的树下的MaterialApp,现在它不能访问BlocConsumer。

谁能指出,处理这种情况的正确方法是什么?混合使用Bloc + Navigator功能是个好主意吗?

您可以使用bloc侦听器侦听注销事件,然后调用navigator函数

可以,您可以将导航嵌入到颤振块中(它在块内为您处理登录/注销导航)。这个解决方案已经存在于flutter_bloc的官方网站上!https://bloclibrary.dev//flutterlogintutorial

最新更新