我是使用 Bloc 和 Cubit 的新手,所以我试图找出一些专门针对 State 组件的最佳实践。我有一个简单的 Todos 应用程序,其中的 Todos 可以处于多种不同的状态:
part of 'todos_cubit.dart';
abstract class TodosState extends Equatable {
const TodosState();
@override
List<Object> get props => [];
}
class TodosLoading extends TodosState {}
class TodosLoaded extends TodosState {
final List<Todo> todos;
TodosLoaded(this.todos);
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is TodosLoaded && listEquals(other.todos, todos);
}
@override
int get hashCode => todos.hashCode;
}
class TodosEmpty extends TodosState {}
class TodosError extends TodosState {
final String error;
TodosError(this.error);
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is TodosError && other.error == error;
}
@override
int get hashCode => error.hashCode;
}
我的问题是,我应该将其保留List<Todo> todos
在TodosLoaded
子类中还是应该将其移至基类?我的想法是,通过将其移至基类,它会使我的TodosEmpty
状态变得多余,因为我可以简单地检查 UI 中的待办事项列表是否为空。如果是这种情况,我是否也应该将其String error
移至基类?
我确信每种方法都有利有弊,只是希望能从任何对 Bloc 有更多经验的人那里获得灵感。