add<T> static method

ValueNotifier<T> add<T>(
  1. String key,
  2. T init()
)

Adds an inherited "value" and listens for its changes. Used in the parent component.

Also removes the listener when the component is disposed.

Implementation

static ValueNotifier<T> add<T>(String key, T Function() init) {
  return VComponent.run((vComponent) {
    final context = VContext(context: vComponent.context, key: _key);
    final Map<String, ValueNotifier> notifiers =
        context.init('notifiers', () => {});
    if (!notifiers.containsKey(key)) {
      try {
        final value = init();
        final notifier = ValueNotifier(value);
        // ignore: prefer_function_declarations_over_variables
        final h = () {
          VRenderer.render(vComponent);
        };

        notifiers[key] = notifier;
        notifier.addListener(h);
        vComponent.addDisposeHandler(vComponent, () {
          notifier.removeListener(h);
        });
        return notifier;
      } catch (e, s) {
        throw WrappedException(
            "An error occurred while executing the method '$InheritedValue.add($key)' for component '$vComponent'",
            e,
            s);
      }
    } else {
      final notifier = notifiers[key];
      return notifier as ValueNotifier<T>;
    }
  });
}