1

我想使用 Firebase 设置身份验证。我有这个 auth 存储库,它具有获取当前用户的方法。

@override
Stream<User?> get user => _firebaseAuth.userChanges();

在我的集团内部,我有这个构造函数。

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final AuthRepository _authRepository;
  late StreamSubscription<User?> _authSubscription;

  AuthBloc(AuthRepository authRepository)
      : _authRepository = authRepository,
        super(const AuthState.initial()) {
    on<AuthStarted>(_onUserChanged);
  }

  void _onUserChanged(AuthStarted event, Emitter<AuthState> emit) {
    _authSubscription = _authRepository.user.listen((user) async {
      if (user != null) {
        emit(AuthState.authenticated(user));
      } else {
        const AuthState.unauthenticated();
      }
    });
  }
}

当我的应用程序启动时,我在我的主课上调用它。

 BlocProvider<AuthBloc>(
            create: (context) => AuthBloc(context.read<AuthRepository>())
              ..add(const AuthEvent.started()),
          ),

这就是我的状态

part of 'auth_bloc.dart';

@freezed
class AuthState with _$AuthState {
  const factory AuthState.initial() = _initial;
  const factory AuthState.authenticated(User user) = _Authenticated;
  const factory AuthState.unauthenticated() = _Unauthenticated;
}

现在我的 UI 上有这个,具体取决于我的应用程序的状态。我想渲染不同的视图。

    return state.when(
      initial: () => _buildInitial(context),
      authenticated: (user) => _buildAuthenticated(),
      unauthenticated: () => _buildUnauthenticated(),
    );

我的集团收到以下错误。

在此处输入图像描述

此处的这一行正在触发错误。

在此处输入图像描述

我正在使用 freezed 包生成 Union,并使用 Bloc 8.0。

4

1 回答 1

2

对于这种情况,我有一个解决方案/解决方法。
让我们创建一个(例如)AuthEvent.onUserDataUpdated(User) 事件,在流侦听器中,您必须使用此事件调用 add() 并为其创建一个处理程序 (on<...>(...)) 以发出新的身份验证状态。

于 2021-12-27T01:14:22.793 回答