如何注销集团模式中的用户



我是Flutter的新手,在一个登录的应用程序中使用flutter_bloc。我的应用程序包含在一个身份验证区块中:

MaterialApp(
home: BlocBuilder<AuthenticationBloc, AuthState>(
builder: (BuildContext context, AuthState state) {
if (state is AuthUnauthenticated) {
return LoginScreen();
} else {
return HomeScreen(); 
}
)
)

问题是,当令牌过期时,存储库中的所有API请求都会返回401,在这种情况下,我想注销用户。以某种方式在这些存储库中检索区块并调度LogOut事件似乎是错误的,打破了模式。

全局处理令牌过期的好方法是什么?我想也许可以从我的UserRepository中与用户创建一个可观察的,然后由集团订阅这个可观察的并调度事件本身。然后我会有一些请求包装器,如果遇到401,它会更改这个可观察的值。

使用BlocProvider和BlocListener,请参阅下面的序列和示例。

  1. 使用BlocProvider将"AuthenticationBloc"传递给子级
  2. 如果由于令牌在子级过期而出现api调用错误
  3. 发送"TokenExpired"事件以查看
  4. 使用"BlocListener"查看接收该消息
  5. 使用"BlocProvider.of"接收"AuthenticationBloc">
  6. 使用"AuthenticationBloc"发送"注销"事件
MaterialApp(
home: BlocProvider(
create: (BuildContext context) => authenticatedBloc,
child: BlocBuilder<AuthenticationBloc, AuthState>(
builder: (BuildContext context, AuthState state) {
if (state is AuthUnauthenticated) {
return LoginScreen();
} else {
return HomeScreen(); 
}
)
)
)
class ChildPage extends StatefulWidget{
...
}
class ChildPageState extends State<ChildPage> {
AuthenticationBloc _authenticationBloc;
@override
void initState() {
super.initState();
_authenticationBloc = BlocProvider.of<AuthenticationBloc>(context);
}
...
@override
Widget build(BuildContext context) {
return BlocListener(
listener: (context, state) {
if (state is TokenExpired) {
_authenticationBloc.add(Loggout());
}
},
child: Container()
....
}


}

最新更新