So, I was working with Django rest framework creating my APIs and all. And i wanted to check if I can get the response from the backend. So, I was able to get the response. But I saw some issues on the debug console. Please help me figure out the problem. This is what I received on the Debug Console.
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.
Here's my source code:
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;
}
The error is pointed on 2nd emit inside loggedIn event handler.
All I had to do was add an await
keyword before calling event.map()
and mark the function with async
as shown below.
Also, I explicitly mentioned what my individual event handlers should return. In this case, it was FutureOr<void>
.
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;
}
Alternatively, we can also replace the map
method with when
in the event handling section (which I prefer to use over map
in scenarios like above). Then, the code would look like this:
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;
}
Note: when
comes from freezed package. It is not a native component of the dart language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With