-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Description
I would like to be able to do WidgetRef.watch/WidgetRef.listen/WidgetRef.listenManual of custom ProviderListenable, not necessarily derived from a Provider.
Let me explain: I would like to be able to do ref.watch of a BLoC/Cubit/ValueListenable/StateNotifier and so on. Creating an adapter between the latter and ProviderListenable
Here is a very hypothetical example of implementation:
extension ProviderValueListenableExtension<T> on ValueListenable<T> {
ProviderListenable<T> get provider => _ValueListenableProvider(this);
}
class _ValueListenableProvider<T> extends ProviderListenable<T> {
final ValueListenable<T> valueListenable;
_ValueListenableProvider(this.valueListenable);
ProviderSubscription<T> addListener(void Function(T? previous, T next) listener) {
T current = valueListenable.value;
void onChange() {
final previous = current;
final next = valueListenable.value;
current = next;
listener(previous, next);
}
valueListenable.addListener(onChange);
return _ValueListenableProviderSubscription(
() => current,
() => valueListenable.removeListener(onChange),
);
}
}
class _ValueListenableProviderSubscription<T> extends ProviderSubscription<T> {
final T Function() reader;
final void Function() listenerRemover;
_ValueListenableProviderSubscription(this.reader, this.listenerRemover);
T read() => reader();
void close() => listenerRemover();
}And one of its uses:
class View extends ConsumerWidget {
final ValueListenable<int> valueListenable;
const View({super.key, required this.valueListenable});
@override
Widget build(BuildContext context, WidgetRef ref) {
final value = ref.watch(valueListenable.provider);
return Text('$value');
}
}That would be really great, it would greatly reduce the code required to manage the various Listenable/ChangeNotifier and allow us to have local StateNotifier/ValueNotifier/Cubit in a widget without having to have them on a Riverpod provider.
I have implemented something similar on this repository base with Riverpod, but I would like to be able to use WidgetRef directly.
What do you think about allowing something like this?