'Flutter Freezed Pakcage Sealed Classes Methods
When I generate sealed classes with Freezed, How can I add methods to the sealed classes?
For example:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'student_state.freezed.dart';
@freezed
abstract class StudentState with _$StudentState {
factory StudentState.loading() = StudentFetchInProgress;
factory StudentState.success(List<int> studentIds) = StudentFetchSuccess;
}
I want to add a function to the StudentFetchSuccess class. I dont know if its possible but I would appreciate even if you tell me its impossible.
Thanks for the help :)
Solution 1:[1]
EDIT: turns out freezed supports this, and there is no need to make the base type abstract. https://github.com/rrousselGit/freezed/tree/master/packages/freezed#mixins-and-interfaces-for-individual-classes-for-union-types
Original answer - also a valid method:
I can't see an easy way. However, the StudentFetchInProgress
and StudentFetchSuccess
are generated as classes (e.g. for use with is
).
So you can use extension methods to add methods to only one of the subclasses. This will only work if you cast your variable to the right type - as the method is called statically.
@freezed
abstract class StudentState with _$StudentState {
factory StudentState.loading() = StudentFetchInProgress;
factory StudentState.success(List<int> studentIds) = StudentFetchSuccess;
}
extension StudentFetchSuccessMethods on StudentFetchSuccess {
void aMethod(){
print("Oh Yeah!");
}
}
void main(){
StudentState state = StudentState.success([]);
state.aMethod(); // this is an error and won't work
if(state is StudentFetchSuccess){
state.aMethod(); // smart casting makes this work
}
}
If you want to add the method to all of the subclasses, the only option I can see is using freezed's when
function. Since StudentState
is abstract it can't have the default constructor freezed needs to add methods to the class, so this will have to be an extension too.
@freezed
abstract class StudentState with _$StudentState {
factory StudentState.loading() = StudentFetchInProgress;
factory StudentState.success(List<int> studentIds) = StudentFetchSuccess;
}
extension StudentStateMethods on StudentState {
void aMethod() {
when(
loading: () => print("Still Loading"),
success: (studentIds) => print("Loaded!"),
);
}
}
void main() {
StudentState state = StudentState.success([]);
state.aMethod(); // this will dynamically call the right function
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |