【问题标题】:Flutter bloc adding 2 event in same timeFlutter bloc同时添加2个事件
【发布时间】:2021-04-20 23:55:59
【问题描述】:

我想在我的应用中检查用户的互联网连接和 Firebase 身份验证状态更改。我正在使用颤振块进行应用程序的状态管理。但是,当在一个 initstate 中调用不同的 2 .add(event) 时,总是第一个运行并更改状态,但第二个没有运行并没有更改状态。我怎么了?

我的集团:

class ControllerBloc extends Bloc<ControllerEvent, ControllerState> {
  ControllerBloc() : super(ControllerInitial());
  AuthApiClient _authApiClient = getIt<AuthApiClient>();

  @override
  Stream<ControllerState> mapEventToState(
    ControllerEvent event,
  ) async* {
    if (event is ControllInternetConnection) {
      yield* internetControll();
    }
    if (event is ControllUserAuth) {
      debugPrint("wwwwgeldi");
      yield* userAuthControl();
    }
    // TODO: implement mapEventToState
  }

  Stream<ControllerState> internetControll() async* {
    Stream<DataConnectionStatus> connectionState =
        DataConnectionChecker().onStatusChange;
    await for (DataConnectionStatus status in connectionState) {
      switch (status) {
        case DataConnectionStatus.connected:
          debugPrint("Bağlandı");
          yield InternetConnectedState();
          break;
        case DataConnectionStatus.disconnected:
          debugPrint("Kesildi");
          yield InternetConnectionLostState();
          break;
      }
    }
  }

  Stream<ControllerState> userAuthControl() async* {
    FirebaseAuth firebaseAuth = _authApiClient.authInstanceAl();
    debugPrint("geldi");
    Stream<User> authStream = firebaseAuth.authStateChanges();

    _authApiClient.authInstanceAl().signOut();

    await for (User authUserResult in authStream) {
      if (authUserResult == null) {
        yield UserAuthControlError();
      }
    }
  }
}

调用我的活动的页面

class _NavigationPageState extends State<NavigationPage> {
  ControllerBloc controllerBloc;

   

  @override
  void initState() {
    controllerBloc= BlocProvider.of<ControllerBloc>(context);
    controllerBloc.add(ControllInternetConnection());
    controllerBloc.add(ControllUserAuth());
    super.initState();
  }

【问题讨论】:

    标签: flutter dart bloc flutter-bloc


    【解决方案1】:

    如果我的理解是正确的,那么在我看来,您正试图用一个 BLoC 解决两个不同的问题。我看不出为什么互联网连接和用户身份验证必须在一个 BLoC 中,而是我将两者分开放在不同的 BLoC 中。

    正如this thread points out 中的讨论,使用 BLoC 的重点围绕着可预测性的目的。您可以覆盖现有的 BLoC 事件流,但我个人认为这对于您想要做的事情来说太复杂了。

    所以我建议,要么制作两个单独的 BLoC,要么将整个过程合并到一个事件中,在用户通过身份验证之前检查互联网连接,然后根据错误返回不同的状态。

    【讨论】:

      猜你喜欢
      • 2019-12-10
      • 2020-11-08
      • 2022-07-26
      • 2023-02-17
      • 2021-12-07
      • 2020-11-12
      • 2022-01-01
      • 2021-03-29
      • 2021-04-25
      相关资源
      最近更新 更多