Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Flutter_bloc provides a state-listening component BlocListener, which calls the callback function given by the listener parameter when the state changes. This method has no return value and can be used to handle reminders such as displaying popup alerts or acknowledgements, displaying status information, etc. With BlocListener, you give us an additional entry point for handling object changes. Next, we use BlocListener to make a second confirmation before logging out of some apps.

The login status

To simplify the logic, our login data has only one enumeration, LoginStatus, with three states:

  • Logon: You have logged in
  • Logout: Indicates that you have logged out
  • LogoutConfirm: Exits and confirms the login

enum LoginStatus { logon, logout, logoutConfirm }

class LoginCubit extends Cubit<LoginStatus> {
  LoginCubit({initial = LoginStatus.logout}) : super(initial);

  void login() => emit(LoginStatus.logon);
  void logout() => emit(LoginStatus.logout);
  void logoutConfirm() => emit(LoginStatus.logoutConfirm);
}
Copy the code

The business logic

We place a button in the center of the screen and switch the button text according to the login status:

  • Logged in: Logout is displayed.
  • Logged out: Displayed as logged in.

When you click the logout button, a second confirmation dialog box will pop up. After confirmation, change the status to Logged out; otherwise, keep the login status unchanged, as shown in the picture below.

Code implementation

Since both our button and BlocListener need to use state data, we use BlocProvider to be placed on top to provide state data for both BlocListener and BlocBuilder.

class BlocListenerWrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    returnBlocProvider( create: (_) => LoginCubit(), child: BlocListenerDemo(), ); }}Copy the code

The code for the BlocListener section is as follows:

class BlocListenerDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BlocListener sample'),
      ),
      body: Center(
        child: BlocListener<LoginCubit, LoginStatus>(
          listener: (context, loginSatus) async {
            if(loginSatus == LoginStatus.logout || loginSatus == LoginStatus.logon) { ScaffoldMessenger.of(context) .. hideCurrentSnackBar() .. showSnackBar(SnackBar( content: Text(loginSatus == LoginStatus.logout ?'Logged out' : 'Login successful'),
                  duration: Duration(seconds: 1))); }else {
              var confirmed = await _confirmLogout(context);
              if (confirmed == true) {
                context.read<LoginCubit>().logout();
              }
            }
          },
          child: BlocBuilder<LoginCubit, LoginStatus>(
            builder: (context, loginSatus) => TextButton(
              child: Text(
                loginSatus == LoginStatus.logon ? 'Log out' : 'login',
                style: TextStyle(
                  fontSize: 24.0,
                ),
              ),
              onPressed: () {
                if (loginSatus == LoginStatus.logon) {
                  context.read<LoginCubit>().logoutConfirm();
                } else {
                  context.read<LoginCubit>().login();
                }
              },
            ),
          ),
        ),
      ),
    );
  }
Copy the code

A SnackBar prompt is displayed when the status is logged in and logged out, and a dialog box pops up if the status is logged in. The LoginCubit logout dialog will return true or false, and if true is used to confirm logout, LoginCubit’s logout will be called to logout. The source code has been submitted to: BLoC state management source code, which runs as follows:

conclusion

As you can see, with BlocListener, you can implement the same effect as a post-blocker, doing additional processing after a state change, such as notifications, or uploading or storing data offline. Handled this way, the coupling of business code can be reduced.

I am dao Code Farmer with the same name as my wechat official account. This is a column about the introduction and practice of Flutter, providing systematic learning articles about Flutter. See the corresponding source code here: The source code of Flutter Introduction and Practical column. If you have any questions, please add me to the wechat account: island-coder.

👍🏻 : feel the harvest please point a praise to encourage!

🌟 : Collect articles, easy to look back!

💬 : Comment exchange, mutual progress!