Closed masus04 closed 1 year ago
You should make your model a listenable object (such as using ChangeNotifier
).
There's no way hooks are going to be able to listen to changes on a plain dart object
You could do:
class Model with ChangeNotifier {
int get count => _count;
int _count =0;
set count(int value) {
_count++:
notifyListeners();
}
}
...
Model useModel() => useMemoized(Model.new, const []);
...
final model = useModel();
// rebuild the UI on model change. Could be done inside useModel itself if you wish
// But doing it outside enables using useListenableSelector too if you want to.
useListenable(model);
return Text(model.count);
You should make your model a listenable object (such as using
ChangeNotifier
). There's no way hooks are going to be able to listen to changes on a plain dart objectYou could do:
class Model with ChangeNotifier { int get count => _count; int _count =0; set count(int value) { _count++: notifyListeners(); } } ... Model useModel() => useMemoized(Model.new, const []); ... final model = useModel(); // rebuild the UI on model change. Could be done inside useModel itself if you wish // But doing it outside enables using useListenableSelector too if you want to. useListenable(model); return Text(model.count);
My main issue is that I don't control the MediaPlayer
object since it's imported from a library. Any solution for that?
Make a wrapper around it
class Model with ChangeNotifier {
final OtherModel _model;
int get count => _model.count;
set count(int value) {
_model.count++;
notifyListeners();
}
}
Is your feature request related to a problem? Please describe. Hooks, like providers, do not seem to rebuild when a complex object changes its values, but only when the object itself is replaced. This behaviour makes sense in most cases, but some times, developers would like a widget to rebuild if a value of a hook object changes.
Consider a media player that has a
PlayerState
. A simple button should display a play icon if thePlayerState
isstopped
and a stop button if thePlayerState
isplaying
.Since the player changes its own internal state, but does not create a new player object, the hook does not rebuild and therefore the icon is not changed.
Describe the solution you'd like I would love to have the option to listen to an attribute of the player and rerender the HookWidget whenever it changes. I could immagine something like this in order to specify an attribute of player that I would like to subscribe to:
This would change the full example to the following:
Describe alternatives you've considered I have tried to simply create a new hook for the
PlayerState
, but then I run into issues where the widget can be disposed of and the hooks are not cleanly disposed, etc.Currently i use the following workaround:
I've also tried to use
useStream
on theplayer.onPlayerStateChanged
stream, but that somehow did not work either, as it did not always rebuild when the state changed.