I basically have a structure like this:
--OuterWidget
--ListWidget
--ListElementWidget1
--ListElementWidget2
...
--ListElementWidget3
WHat I wanna do is the following: whenever a user checks a checkbox in ListElementWidget, I want to be notified about that in OuterWidget. Also, whenever I add an element to the list in OuterWidget, I want that to be reflected in ListWidget. I could do the simple method of passing down a notifier in constructor, but is there a simpler way?
CodePudding user response:
Welcome to the world of State Management!
The easiest way to know if a checkbox changed in ListElementWidget
is passing a callback method down the chain, like you've already mentioned, then calling that when the user checks a checkbox.
OuterWidget() => ListWidget(toggleCheckCallBack) => ListElementWidget(toggleCheckCallBack);
And, for the updating of the ListWidget
, simply making OuterWidget
a StatefulWidget
and calling setState
when an element is added should resolve that too.
While this does solve the issue, it probably wouldn't scale well, if you believe this is a problem, take a look at the various state management libraries Flutter has.
CodePudding user response:
Look at stateful widgets
void onPressed() {
setState(() {
// Here you can set values in your widget
// and it will update all widgets in state.
});
}
Sorry if code wrong I am typing from memory... Full code example:
class Page extends StatefulWidget {
@override
State createState(BuildContext context) => _PageState();
}
class _PageState extends State<Page> {
int someValue = 0;
Widget build() => TextButton(
text: Text(someValue.toString()),
onPress: () => SetState(() {
someValue = 4;
})
)
}