在同一页面中使用两个BLoC,并在第二个BLoC中传递第一个BLoC的状态

时间:2020-10-30 10:10:47

标签: flutter dart state bloc chopper

几天来我一直在学习Flutter中的Bloc模式。

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

  2. 有两个实现此功能的API(generateOtp,validateOtp)。

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

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

  5. 我已经创建了两个单独的BLoC ... generateOtpBloc,validateOtpBloc。

  6. 使用MultiBLoC提供程序我正在使用这两个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. 我能够在我的UI页面中调用API并获取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。

对我来说,解决这个问题的最好方法是什么?

1 个答案:

答案 0 :(得分:1)

为什么您尝试使用两个bloc来处理它?您可以在一个event中使用两个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类! 希望对您有用。