这几天我一直在学习 Flutter 中的 Bloc Pattern。
Navigator.of(context).push(
MaterialPageRoute<LandingPage>(
builder: (_) => MultiBlocProvider(
providers: [
BlocProvider<GenerateOtpBloc>(
create: (context) => GenerateOtpBloc(GenerateOtpInitial())
),
BlocProvider<ValidateOtpBloc>(
create: (context) => ValidateOtpBloc(ValidateOtpInitial())
)
],
child: OtpPage(),
),
),
);
但是如何保存我在 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 的原因。向我建议处理此问题的最佳方法?
最佳答案
为什么你尝试使用两个 bloc
s 来处理它吗?您可以使用两个 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 类!我希望它对你有用。
关于flutter - 在同一页面中使用两个 BLoC 并在第二个 BLoC 中传递第一个 BLoC 的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64606353/