我在 user_bloc.dart 中有這段代碼:
UserBloc(this._userRepository, UserState userState) : super(userState) {
on<RegisterUser>(_onRegisterUser);
}
void _onRegisterUser(RegisterUser event, Emitter<UserState> emit) async {
emit(UserRegistering());
try {
// detect when the user is registered
FirebaseAuth.instance.authStateChanges().listen((User? user) async {
if (state is UserRegistering && user != null) {
// save user to db
try {
await _userRepository.addUpdateUserInfo(user.uid, userInfo);
} catch (e) {
emit(UserRegisteringError("Could not save user"));
}
emit(UserLoggedIn(user));
}
});
... call FirebaseAuth.instance.createUserWithEmailAndPassword
這是 _userRepository.addUpdateUserInfo:
Future<void> addUpdateUserInfo(String userId, UserInfo userInfo) async {
try {
var doc = usersInfo.doc(userId);
await doc.set(
{
'first_name': userInfo.firstName,
'last_name': userInfo.lastName,
'email': userInfo.email
},
SetOptions(merge: true),
);
} catch (e) {
print("Failed to add user: $e");
throw Exception("Failed to add user");
}
}
當emit(UserLoggedIn(user));被呼叫時,我收到此錯誤:
Error: Assertion failed:
..\…\src\emitter.dart:114
!_isCompleted
"\n\n\nemit was called after an event handler completed normally.\nThis is usually due to an unawaited future in an event handler.\nPlease make sure to await all asynchronous operations with event handlers\nand use emit.isDone after asynchronous operations before calling emit() to\nensure the event handler has not completed.\n\n **BAD**\n on<Event>((event, emit) {\n future.whenComplete(() => emit(...));\n });\n\n **GOOD**\n on<Event>((event, emit) async {\n await future.whenComplete(() => emit(...));\n });\n"
at Object.throw_ [as throw] (http://localhost:58334/dart_sdk.js:5067:11)
at Object.assertFailed (http://localhost:58334/dart_sdk.js:4992:15)
at _Emitter.new.call (http://localhost:58334/packages/bloc/src/transition.dart.lib.js:765:40)
at user_bloc.UserBloc.new.<anonymous> (http://localhost:58334/packages/soli/blocs/bloc/user_bloc.dart.lib.js:90:20)
at Generator.next (<anonymous>)
at http://localhost:58334/dart_sdk.js:40571:33
at _RootZone.runUnary (http://localhost:58334/dart_sdk.js:40441:59)
at _FutureListener.thenAwait.handleValue (http://localhost:58334/dart_sdk.js:35363:29)
at handleValueCallback (http://localhost:58334/dart_sdk.js:35931:49)
at Function._propagateToListeners (http://localhost:58334/dart_sdk.js:35969:17)
at _Future.new.[_completeWithValue] (http://localhost:58334/dart_sdk.js:35817:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:58334/dart_sdk.js:35838:35)
at Object._microtaskLoop (http://localhost:58334/dart_sdk.js:40708:13)
at _startMicrotaskLoop (http://localhost:58334/dart_sdk.js:40714:13)
at http://localhost:58334/dart_sdk.js:36191:9
[2022-02-17T03:47:00.057Z] @firebase/firestore:
收到錯誤后,如果我再次嘗試使用其他用戶,它可以正常作業。
uj5u.com熱心網友回復:
這是預期的結果,因為該_onRegisterUser方法已經完成執行,但內部的代碼FirebaseAuth.instance.authStateChanges().listen(...)試圖在之后發出狀態更改。
在這種情況下,您可以做什么,而不是在 FirebaseAuth 偵聽器中發出新狀態,您應該向 BLoC 添加新事件:
if (state is UserRegistering && user != null) {
// save user to db
try {
await _userRepository.addUpdateUserInfo(user.uid, userInfo);
} catch (e) {
add(RegistrationErrorEvent()); // Create this event
}
add(UserLoggedInEvent(user: user)); // Create this event
}
然后,您應該注冊這些事件并處理邏輯:
UserBloc(this._userRepository, UserState userState) : super(userState) {
on<RegisterUser>(_onRegisterUser);
on<RegistrationErrorEvent>((event, emit) => emit(UserRegisteringError("Could not save user")));
on<UserLoggedInEvent>((event, emit) => emit(UserLoggedIn(event.user)));
}
此外,由于您正在使用流和listen方法,StreamSubscription因此請考慮使用,以便在偵聽狀態更改后清理資源。
這是來自 GitHub 上的 bloc 存盤庫的示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/426599.html
