Skip to content

I would like to be able to do WidgetRef.watch/WidgetRef.listen/WidgetRef.listenManual of custom ProviderListenable, not necessarily derived from a Provider. #4391

@BreX900

Description

@BreX900

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?

Originally posted by @BreX900 in #4389

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions