【问题标题】:Flutter Bloc How to emit inside a listenerFlutter Bloc 如何在监听器内部发射
【发布时间】:2023-03-29 13:51:02
【问题描述】:

我想使用 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。

【问题讨论】:

  • 错误说你需要像 Future _onUserChanged(AuthStarted event, Emitter emit) async { ...
  • 是的,但不知道如何等待流。

标签: flutter flutter-bloc freezed


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 2020-03-26
    • 2021-02-20
    • 2020-03-27
    • 2020-06-15
    • 2023-03-24
    • 2021-06-27
    • 2020-02-18
    相关资源
    最近更新 更多