如何访问基本状态类中不存在的集体状态属性?
考虑以下状态:
class ExerciseInitialState extends ExerciseState {}
class ExerciseLoadingState extends ExerciseState {}
class ExerciseLoadedState extends ExerciseState {
final List<Data> data;
const ExerciseLoadedState({required this.data});
@override
List<Object> get props => [data];
// total count
int get totalCount => data.length;
}
在UI中,我必须将状态(exropiseState
)施加到ercoresEloAdedState
,以便能够访问其属性,该属性在>中不存在练习载体
和corameInitialState
:
final total = (context.read<ExerciseBloc>().state as ExerciseLoadedState).totalCount
必须始终进行此操作对我来说似乎很尴尬。是将相同属性添加到基类exromisesestate
的唯一解决方案?
Consider these states:
class ExerciseInitialState extends ExerciseState {}
class ExerciseLoadingState extends ExerciseState {}
class ExerciseLoadedState extends ExerciseState {
final List<Data> data;
const ExerciseLoadedState({required this.data});
@override
List<Object> get props => [data];
// total count
int get totalCount => data.length;
}
In the UI, I have to cast the state (ExerciseState
) to ExerciseLoadedState
to be able to access its property which doesn't exist in the ExerciseLoadingState
and ExerciseInitialState
:
final total = (context.read<ExerciseBloc>().state as ExerciseLoadedState).totalCount
It looks awkward to me to have to do this casting all the time. Is the only solution to add the same properties to the base class ExerciseState
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它不应该对您感到不对 - 如果您希望该属性在所有州类中可用,则应在基类中定义。例如,您无法获得
totalCount
,而状态为erecoreSeloAdingState
仅仅是因为此属性在此处未定义 - 您需要将类型推广到特定类型。这个问题有两种可能的解决方案:
exromiseSeloAdedState
访问属性:ercorysestate
上创建扩展方法:使用扩展,您无需在UI层中进行类型促销。
It should not feel wrong to you - if you want the property to be available in all the state classes, it should be defined in the base class. E.g. you cannot get the
totalCount
while the state isExerciseLoadingState
simply because this property is not defined here - you need to promote the type to a specific one.There are two possible solutions to this problem:
ExerciseLoadedState
to access the property:ExerciseState
:With the extension, you won't need to do the type promotion in your UI layer.