flutter_bloc(在事件处理程序正常完成后调用发出

Posted

技术标签:

【中文标题】flutter_bloc(在事件处理程序正常完成后调用发出【英文标题】:flutter_bloc (emit was called after an event handler completed normally 【发布时间】:2022-01-10 20:18:35 【问题描述】:

所以,我正在使用 Django REST 框架创建我的 API 和所有内容。 我想检查我是否可以从后端获得响应。 所以,我能够得到回应。但是我在调​​试控制台上看到了一些问题。请帮我找出问题所在。 这是我在调试控制台上收到的。

Restarted application in 1,314ms.
I/flutter ( 1751): "token":"0d15f2d45f11869174395d623c066080bd2ade52"
E/flutter ( 1751): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: 'package:bloc/src/bloc.dart': Failed assertion: line 232 pos 7: '!_isCompleted':
E/flutter ( 1751):
E/flutter ( 1751):
E/flutter ( 1751): emit was called after an event handler completed normally.
E/flutter ( 1751): This is usually due to an unawaited future in an event handler.
E/flutter ( 1751): Please make sure to await all asynchronous operations with event handlers
E/flutter ( 1751): and use emit.isDone after asynchronous operations before calling emit() to
E/flutter ( 1751): ensure the event handler has not completed.
E/flutter ( 1751):
E/flutter ( 1751):   **BAD**
E/flutter ( 1751):   on<Event>((event, emit) 
E/flutter ( 1751):     future.whenComplete(() => emit(...));
E/flutter ( 1751):   );
E/flutter ( 1751):
E/flutter ( 1751):   **GOOD**
E/flutter ( 1751):   on<Event>((event, emit) async 
E/flutter ( 1751):     await future.whenComplete(() => emit(...));
E/flutter ( 1751):   );
E/flutter ( 1751):
E/flutter ( 1751): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter ( 1751): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter ( 1751): #2      _Emitter.call
E/flutter ( 1751): #3      new LoginFormBloc.<anonymous closure>.<anonymous closure>
E/flutter ( 1751): <asynchronous suspension>
E/flutter ( 1751):
Reloaded 1 of 746 libraries in 1,055ms.

这是我的源代码:

login_form_event.dart

part of 'login_form_bloc.dart';

@freezed
class LoginFormEvent with _$LoginFormEvent 
  const factory LoginFormEvent.emailChanged(String emailStr) = _EmailChanged;
  const factory LoginFormEvent.passwordChanged(String passwordStr) =
      _PasswordChanged;
  const factory LoginFormEvent.loggedIn() = _LoggedIn;

login_form_state.dart

part of 'login_form_bloc.dart';

@freezed
class LoginFormState with _$LoginFormState 
  const factory LoginFormState(
    required EmailAddress emailAddress,
    required Password password,
    required bool isSubmitting,
    required bool showErrorMessages,
    required Option<Either<AuthFailure, TokenValue>> authFailureOrSuccessOption,
  ) = _LoginFormState;

  factory LoginFormState.initial() => LoginFormState(
        emailAddress: EmailAddress(''),
        password: Password(''),
        isSubmitting: false,
        showErrorMessages: false,
        authFailureOrSuccessOption: none(),
      );

login_form_bloc.dart

class LoginFormBloc extends Bloc<LoginFormEvent, LoginFormState> 
  LoginFormBloc(this._getAuthInfo) : super(LoginFormState.initial()) 
    on<LoginFormEvent>(
      (event, emit) 
        event.map(
          emailChanged: (e) 
            emit(
              state.copyWith(
                emailAddress: EmailAddress(e.emailStr),
                authFailureOrSuccessOption: none(),
              ),
            );
          ,
          passwordChanged: (e) 
            emit(
              state.copyWith(
                password: Password(e.passwordStr),
                authFailureOrSuccessOption: none(),
              ),
            );
          ,
          loggedIn: (e) async 
            final isEmailValid = state.emailAddress.value.isRight();
            final isPasswordValid = state.password.value.isRight();

            Either<AuthFailure, TokenValue>? loginFailureOrSuccess;

            if (isEmailValid && isPasswordValid) 
              emit(
                state.copyWith(
                  isSubmitting: true,
                  authFailureOrSuccessOption: none(),
                ),
              );
              loginFailureOrSuccess = await _getAuthInfo(
                Params(
                  emailAddress: state.emailAddress,
                  password: state.password,
                ),
              );
            

         //The error is pointed to this emit below
            emit(
              state.copyWith(
                isSubmitting: false,
                showErrorMessages: true,
                authFailureOrSuccessOption: optionOf(loginFailureOrSuccess),
              ),
            );
          ,
        );
      ,
    );
  
  final GetAuthToken _getAuthInfo;

错误是在loggedIn事件处理程序内的第二次发出时指出的。

【问题讨论】:

map 方法是怎么回事?为什么不使用普通的on&lt;Event&gt; 表示法,它可能会解决问题......如果你不想使用普通的on 方法,你能展示一下map 方法的实现吗? map 方法在那里是因为我使用了 freezed 包提供的 unions。 @h8moss 查看更新后的帖子。也许这会有所帮助。 问题已经解决了。 我明白了,很高兴听到问题得到解决 【参考方案1】:

我所要做的就是在调用event.map() 之前添加一个await 关键字并用async 标记函数,如下所示。 此外,我明确提到了我的个人事件处理程序应该返回什么。在这种情况下,它是FutureOr&lt;void&gt;

class LoginFormBloc extends Bloc<LoginFormEvent, LoginFormState> 
  LoginFormBloc(this._getAuthInfo) : super(LoginFormState.initial()) 
    on<LoginFormEvent>(
      (event, emit) async 
        await event.map<FutureOr<void>>(  // Added an await in this line
          emailChanged: (e) 
            emit(
              state.copyWith(
                emailAddress: EmailAddress(e.emailStr),
                authFailureOrSuccessOption: none(),
              ),
            );
          ,
          passwordChanged: (e) 
            emit(
              state.copyWith(
                password: Password(e.passwordStr),
                authFailureOrSuccessOption: none(),
              ),
            );
          ,
          loggedIn: (e) async 
            final isEmailValid = state.emailAddress.value.isRight();
            final isPasswordValid = state.password.value.isRight();

            Either<AuthFailure, TokenValue>? loginFailureOrSuccess;

            if (isEmailValid && isPasswordValid) 
              emit(
                state.copyWith(
                  isSubmitting: true,
                  authFailureOrSuccessOption: none(),
                ),
              );
              loginFailureOrSuccess = await _getAuthInfo(
                Params(
                  emailAddress: state.emailAddress,
                  password: state.password,
                ),
              );
            
            emit(
              state.copyWith(
                isSubmitting: false,
                showErrorMessages: true,
                authFailureOrSuccessOption: optionOf(loginFailureOrSuccess),
              ),
            );
          ,
        );
      ,
    );
  
  final GetAuthToken _getAuthInfo;

或者,我们也可以在事件处理部分用when 替换map 方法(在上述情况下,我更喜欢使用map)。然后,代码将如下所示:

class LoginFormBloc extends Bloc<LoginFormEvent, LoginFormState> 
  LoginFormBloc(this._getAuthInfo) : super(LoginFormState.initial()) 
    on<LoginFormEvent>(
      (event, emit) async 
        await event.when<FutureOr<void>>(  // Replace map with when
          emailChanged: (emailStr)   // Can directly pass String instead of _EmailChanged object
            emit(
              state.copyWith(
                emailAddress: EmailAddress(emailStr),  // Can directly pass emailStr as shown
                authFailureOrSuccessOption: none(),
              ),
            );
          ,
          passwordChanged: (passwordStr) 
            emit(
              state.copyWith(
                password: Password(passwordStr),
                authFailureOrSuccessOption: none(),
              ),
            );
          ,
          loggedIn: () async 
            final isEmailValid = state.emailAddress.value.isRight();
            final isPasswordValid = state.password.value.isRight();

            Either<AuthFailure, TokenValue>? loginFailureOrSuccess;

            if (isEmailValid && isPasswordValid) 
              emit(
                state.copyWith(
                  isSubmitting: true,
                  authFailureOrSuccessOption: none(),
                ),
              );
              loginFailureOrSuccess = await _getAuthInfo(
                Params(
                  emailAddress: state.emailAddress,
                  password: state.password,
                ),
              );
            
            emit(
              state.copyWith(
                isSubmitting: false,
                showErrorMessages: true,
                authFailureOrSuccessOption: optionOf(loginFailureOrSuccess),
              ),
            );
          ,
        );
      ,
    );
  
  final GetAuthToken _getAuthInfo;

注意:when 来自 freezed package。它不是 dart 语言的原生组件。

【讨论】:

以上是关于flutter_bloc(在事件处理程序正常完成后调用发出的主要内容,如果未能解决你的问题,请参考以下文章

从 v7.2.1 迁移到 flutter_bloc v 8.0.0 后不会触发 flutter_bloc 事件

Flutter_bloc 从没有 UI 事件的 firestore 获取更新的数据

在使用 flutter_bloc 库调度事件之前等待一些结果

flutter_bloc 4.0.0如何获取事件属性参数。

重叠 I/O:如何在完成端口事件或正常事件上唤醒线程?

如何为 MFC 中的线程完成添加事件处理程序?