I'm trying to make a state class for my todo bloc, and I want to keep the loaded todos when I start refreshing. Is there a better way to do this, basically having a mutual field in all the constructors of the class using freezed package
@freezed
class TodoState with _$TodoState {
const factory TodoState.loading(List<Todo> todos) = TodoStateLoading;
const factory TodoState.loaded(List<Todo> todos) = TodoStateLoaded;
const factory TodoState.error(List<Todo> todos, String message) = TodoStateError;
}
I can already use it like this, but i would like to just call state.todos and not having to check for its type:
TodoState state = TodoStateLoaded([/*example*/]);
state.todos // ERROR
(state as TodoStateLoaded).todos // OK
As per this comment freezed do not support super classes. The closest solution that might work for you is this:
// create mixin with getter of properties that you would like to share between states
mixin TodoMixin {
List<Todo> get todos;
}
@freezed
// add mixin to your class with state
class TodoState with TodoMixin, _$TodoState {
const TodoState._(); // add private constructor
//override getter with map function that will return data for each state
@override
List<Todo> get todos {
return map(
loading: (state) => state.todos,
loaded: (state) => state.todos,
error: (state) => state.todos,
);
}
const factory TodoState.loading(List<Todo> todos) = TodoStateLoading;
const factory TodoState.loaded(List<Todo> todos) = TodoStateLoaded;
const factory TodoState.error(List<Todo> todos, String message) = TodoStateError;
}
It will create common getter for state and when you will introduce new state map
method will show you, that you need handle new state in getter. Add another property in mixin and you will need override it too.
To use it you can call it in cubit:
state.todos;
or in view: context.read<TodoCubit>().state.todos;