'How to build a hierarchical state-notifier structure?
I am trying to split my state notifiers into a parent/child hierarchy but I am not sure how to approach that.
//I want this to be a parent controller that keeps the "index" for its child in its own state.
// "ParentState" is a freezed dataclass so inheriting from it is not possible.
class ParentController extends StateNotifier<ParentState>{
ParentController(ParentState state) : super(state);
//Every "ChildController" needs to have this method.
void setIndex(int index){
state = state.copyWith(index: index);
}
}
// "ChildState" is a freezed dataclass.
class ChildController extends StateNotifier<ChildState> implements ChildController {
ChildController (ChildState state) : super(state);
//this controller should have access to the parents index and update
//if the parents "setIndex" is called.
}
So a successful implementation would look like this:
final childController = ChildController();
childControllerOne.setIndex(2);
childControllerOne.index == 2 //true;
Because I have multiple ChildControllers, my goal is to put as much shared code in this parent controller and state, so that I don't have to repeat myself.
My current solution is a mixin like this:
mixin SetIndexMixin {
void setIndex(int index){
onSetIndex(index);
}
void onIndexSet(int index);
}
which I implement like so :
class ChildController extends StateNotifier<ChildState> with SetIndexMixin {
ChildController (ChildState state) : super(state);
@override
onIndexSet(int index){
state = state.copyWith(index);
}
}
But I feel like there has to be a more elegant and scalable solution.
Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
