while discovering Getx
source code, I faced a piece of code that make me confused, it's not related 100% to Getx
. it's about SetState(() {})
so, in the Getx
there is a state update that targets only the widgets with a specific id:
Disposer addListenerId(Object? key, GetStateUpdate listener) {
_updatersGroupIds![key] ??= <GetStateUpdate>[];
_updatersGroupIds![key]!.add(listener);
return () => _updatersGroupIds![key]!.remove(listener);
}
the _updatersGroupIds
is a HashMap<Object?, List<void Function()>>?
.
and when calling it from the StatefulWidget
, like this :
controller?.addListenerId(
widget.id,
setState(() {}),
);
the id
is passed from a property in the widget call, and as you see it's passing the whole SetState(() {})
of that StatefulWidget
in the function!
so the _updatersGroupIds
will be something like this :
_updatersGroupIds == {
"idExample": [
SetState(() {}),
]
};
right?
what confused me is when we try to update the state we call the update
method from the controller with desirables ids to update :
update(["idExample"]);
this is implemented as follows:
void update([List<Object> ids]) {
for (final id in ids) {
if (_updatersGroupIds!.containsKey(id)) {
final listGroup = _updatersGroupIds![id]!;
for (var item in listGroup) {
item();
}
}
}
}
so what I understand is that when we get the "exampleId" in the _updatersGroupIds
hashmap, we iterate over all the SetState(() {})
in that list, by calling them
so what I'm expecting vs what happens :
what I'm expecting:
that since we called all the SetState(() {})
in that List
, it will update the State
of all StateFulWidget
in the whole app, or at least it will update the last StatefulWidget
we run that function from.
what is happening:
it updates only the StatefulWidget
with the same "exampleId", and nothing else
my question is: how when we store the SetState(() {})
of multiple widgets like :
List<void Function()> staterList = [SetState(() {}), SetState(() {}), SetState(() {})];
when we call the second one:
staterList[1].call();
how does it know that it should update only the StatefulWidget
where that SetState((){})
came from and nothing else?
another format of question:
is there some referencing set on SetState(() {})
, so that it knows the StateFulWidget
where it came from when we call it somewhere outside?
please share your knowledge with me.