简体   繁体   中英

How to log out user in the bloc pattern?

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.

  1. pass the 'AuthenticationBloc' to child by using BlocProvider.
  2. if there is api call error because of token expires at child
  3. send 'TokenExpired' event to view
  4. view receive that message by using 'BlocListener'
  5. receive 'AuthenticationBloc' by using 'BlocProvider.of'.
  6. send 'Logout' event by using '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()
      ....
}
          


}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM