I am new to Flutter and I am using flutter_bloc
in an app with a login. My app is wrapped in an authentication bloc:
MaterialApp(
home: BlocBuilder<AuthenticationBloc, AuthState>(
builder: (BuildContext context, AuthState state) {
if (state is AuthUnauthenticated) {
return LoginScreen();
} else {
return HomeScreen();
}
)
)
The problem is that all my API requests in repositories can return 401 when the token expires and in this case I want to log out the user. It seems wrong and breaking the pattern to somehow retrieve the bloc in those repositories and dispatch LogOut
event.
What would be a good way to globally handle the token expiration? I thought maybe creating an observable with the user from my UserRepository
and then the bloc subscribing to this observable and dispatching events itself. Then I would have some request wrapper that would change this observable value if it encountered 401.
Using BlocProvider and BlocListener, refer to below sequence and example.
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()
....
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.