跳转RegistrationSendCode页面触发StateError异常,请求排查原因
状态错误问题排查与修复
问题根源分析
1. Cubit初始状态未正确设置
你的RegistrationSendCodeCubit在实例化时没有指定初始状态为RegistrationSendCodeNotLoading,导致BlocBuilder接收到的初始状态不匹配任何分支,最终触发StateError('err')。
2. 分支缺少return语句
在RegistrationSendCodeNotLoading的判断分支中,仅调用了RegistrationSendCodeWidget()但未使用return返回该组件,即使状态匹配也会继续执行后续逻辑,最终走到错误抛出代码。
修复代码
步骤1:设置Cubit初始状态
修改RegistrationSendCodeCubit的构造函数,明确指定初始状态:
class RegistrationSendCodeCubit extends Cubit<RegistrationSendCodeState> { RegistrationSendCodeCubit() : super(RegistrationSendCodeNotLoading()); // 你的业务逻辑方法 }
步骤2:补充return语句
修正RegistrationSendCodeBuilder中的BlocBuilder逻辑:
class RegistrationSendCodeBuilder extends StatelessWidget { @override Widget build(BuildContext context) { return BlocBuilder<RegistrationSendCodeCubit, RegistrationSendCodeState>( builder: (context, state) { if(state is RegistrationSendCodeNotLoading) { return RegistrationSendCodeWidget(); // 补充return } else if(state is RegistrationSendCodeLoading) { return const Scaffold( body: Center(child: CircularProgressIndicator(),), ); } else if(state is RegistrationSendCodeLoaded) { return FullName(); } else if(state is RegistrationSendCodeError) { return MyError(); } throw StateError('err'); }, ); } }
修复后,Cubit初始化时会直接进入RegistrationSendCodeNotLoading状态,同时该分支会正确返回对应的组件,不会触发状态错误。
内容的提问来源于stack exchange,提问作者Daniil
相关产品推荐
相关产品推荐

