0

这几天我一直在学习 Flutter 中的 Bloc Pattern。

  1. 我有一个页面需要生成 OTP 并对其进行验证。

  2. 有两个 API(generateOtp、validateOtp)两个实现了这个功能。

  3. 在 generateOtp API 响应中,我需要保存一个密钥,即 uniqueIdentifier。

  4. 然后我需要将上面的 uniqueIdentifier 和 Otp 值(用户输入)传递给 validateOtp API。

  5. 我创建了两个单独的 BLoC... generateOtpBloc、validateOtpBloc。

  6. 使用 MultiBLoC Provider 我正在使用这两个 BLoC。

                            Navigator.of(context).push(
                              MaterialPageRoute<LandingPage>(
                                builder: (_) => MultiBlocProvider(
                                  providers: [
                                    BlocProvider<GenerateOtpBloc>(
                                      create: (context) => GenerateOtpBloc(GenerateOtpInitial())
                                    ),
                                    BlocProvider<ValidateOtpBloc>(
                                      create: (context) => ValidateOtpBloc(ValidateOtpInitial())
                                    )
                                  ],
                                  child: OtpPage(),
                                ),
                              ),
                            );
  1. 我能够调用 API 并在我的 UI 页面中获取 API 响应。

但是如何保存我在 generateOtp 中获得的 uniqueIdentifier 值以及如何在第二个 API 中传递这个 uniqueIdentifier?

我想到了使用 setState() 来设置 uniqueIdentifier 的状态。但我收到一个错误。

          child: BlocBuilder<GenerateOtpBloc, GenerateOtpState>(
            builder: (context, state) {
              if (state is GenerateOtpLoading) {
                print("**********GenerateOtpLoading*************");

                return buildLoading();
              } else if (state is GenerateOtpLoaded) {
                print("**********GenerateOtpLoaded*************");

                ***//But Im getting error here.***
                ***setState(() {
                  uniqueIdentifier: state.uniqueIdentifier
                });***

                return buildGenerateOtpWidget(context, state.generateOtpRes);
              } else {
                print("**********Else*************");
                print(state);
              }
            },
          ),
        ),

generateOtp 和 validateOtp 请求和响应都完全不同……这就是我使用两个不同 BLoC 的原因。

向我建议处理此问题的最佳方法?

4

1 回答 1

1

为什么您尝试使用两个blocs 来处理它?您可以将两个events 合二为一bloc。这是我在 OTP 登录项目中的代码,类似于您的项目:

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  FirstApiClass _firstApi;
  SecondApiClass _secondApi;

  LoginBloc() : super(Loading()) {
    _firstApi = FirstApiClass();
    _secondApi = SecondApiClass();
  }

  @override
  Stream<LoginState> mapEventToState(
    LoginEvent event,
  ) async* {
      if (event is GenerateOtp) {
        // Use FirstApiClass
      } else if (event is ValidateOtpBloc) {
        // Use SecondApiClass
      }
  }
}

但是,您也可以在这种情况下使用一个 Api 类!我希望它对你有用。

于 2020-10-30T11:02:59.770 回答