Switch Case类型不匹配报错:如何适配SelectFieldBloc与String类型?
问题解决:Switch Case类型不匹配报错
报错翻译
原报错:The switch case expression type 'String' must be a subtype of the switch expression type 'SelectFieldBloc<String, dynamic>'
翻译:switch case的表达式类型String必须是switch表达式类型SelectFieldBloc<String, dynamic>的子类型
核心问题
你直接将SelectFieldBloc<String, dynamic>类型的对象_formBloc作为switch的判断表达式,但case分支里写的是字符串/数字值,两者类型不匹配。switch的表达式和case值必须是同一类型。
解决方案
1. 针对SelectFieldBloc<String, dynamic>类型的_formBloc
你需要取bloc的当前值(value属性)来做判断,同时统一case值的类型(因为bloc泛型是String,所以case要全部用字符串):
switch(_formBloc.value) { case 'Option 1': return Text("zero widget"); case '1': return Text("one widget"); case '2': return Text("two widget"); case '3': return Text("three widget"); case '4': return Text("three widget"); case '5': return Text("three widget"); default: return Text("default widget"); }
如果是在BlocBuilder中使用,建议通过state.value获取最新值:
BlocBuilder<SelectFieldBloc<String, dynamic>, SelectFieldBlocState<String, dynamic>>( builder: (context, state) { switch(state.value) { case 'Option 1': return Text("zero widget"); case '1': return Text("one widget"); // 其他case分支 default: return Text("default widget"); } }, )
2. 针对你提供的filepicker2(InputFieldBloc<PlatformFile?, Object>)
如果_formBloc实际是这个InputFieldBloc,它的value类型是PlatformFile?,你需要取PlatformFile的具体属性(比如name/id)来做判断:
final selectedFile = _formBloc.value; switch(selectedFile?.name) { // 替换为你实际要判断的属性 case 'Option 1': return Text("zero widget"); // 根据实际属性值编写case分支 default: return Text("default widget"); }
内容的提问来源于stack exchange,提问作者1988
相关产品推荐
相关产品推荐

