createSignal<T> function

  1. @Deprecated('use SignalsMixin > createSignal instead')
Signal<T> createSignal<T>(
  1. BuildContext context,
  2. T value, {
  3. String? debugLabel,
  4. bool autoDispose = true,
})

Create and watch a signal and rebuild on changes.

class State extends ... {
 late final count = createSignal(context, 0);

 @override
 Widget build(BuildContext context) {
   return Row(
    children: [
      IconButton(icon: Icon(Icons.remove), onPressed: () => count.value--),
      Text(count.value.toString()),
      IconButton(icon: Icon(Icons.add), onPressed: () => count.value++),
   ],
  );
 }
}

Implementation

@Deprecated('use SignalsMixin > createSignal instead')
Signal<T> createSignal<T>(
  BuildContext context,
  T value, {
  String? debugLabel,
  bool autoDispose = true,
}) {
  assert(
    allowSignalsCreatedInBuildContext ? true : context is StatefulElement,
    'createSignal must be called in a StatefulElement like State<T>',
  );
  Signal<T> result;
  if (allowSignalsCreatedInBuildContext) {
    final key = (value, debugLabel, autoDispose).hashCode;
    if (_signals[key]?.target == null || _signals[key]?.target is! Signal<T>) {
      _signals.remove(key);
    }
    final target = _signals[key] ??= () {
      final source = signal<T>(
        value,
        debugLabel: debugLabel,
        autoDispose: autoDispose,
      );
      final ref = WeakReference(source);
      source.onDispose(() => _signals.remove(key));
      return ref;
    }();
    result = target.target as Signal<T>;
  } else {
    result = signal<T>(
      value,
      debugLabel: debugLabel,
      autoDispose: autoDispose,
    );
  }
  return bindSignal<T, Signal<T>>(context, result);
}