manageChangeNotifier<T extends ChangeNotifier> function

ReadonlyRef<T> manageChangeNotifier<T extends ChangeNotifier>(
  1. T notifier
)

Manages a ChangeNotifier with automatic lifecycle management.

Similar to manageListenable, but also handles disposal of the ChangeNotifier when the component unmounts.

Use this for controllers and other ChangeNotifier instances that you create and need to dispose.

Example:

@override
Widget Function(BuildContext) setup() {
  final controller = ScrollController();
  final reactiveController = manageChangeNotifier(controller);

  final scrollOffset = computed(() {
    reactiveController.value; // Track changes
    return controller.offset;
  });

  return (context) => ListView(
    controller: controller,
    children: [...],
  );
}

Implementation

ReadonlyRef<T> manageChangeNotifier<T extends ChangeNotifier>(T notifier) {
  final custom = ReadonlyCustomRef<T>(
    getter: (track) {
      track();
      return notifier;
    },
  );

  void listener() {
    custom.trigger();
  }

  notifier.addListener(listener);

  onUnmounted(() {
    notifier
      ..removeListener(listener)
      ..dispose();
  });

  return custom;
}