Observable<T> class

A reactive holder of a value of type T.

Reading value inside an Observer builder automatically registers that Observer to rebuild when the value changes. Observable also implements ValueListenable, so it is directly usable with ValueListenableBuilder, Listenable.merge, or AnimatedBuilder without any adapter.

Notification semantics are intentionally simple: a write only notifies listeners when the new value is different from the current one (!=). For mutable objects whose internal state changed without replacing the reference, call refresh to force a notification.

Um contêiner reativo de um valor do tipo T.

Ler value dentro do builder de um Observer registra automaticamente aquele Observer para reconstruir quando o valor mudar. Observable também implementa ValueListenable, portanto é utilizável diretamente com ValueListenableBuilder, Listenable.merge ou AnimatedBuilder sem nenhum adaptador.

A semântica de notificação é propositalmente simples: uma escrita só notifica os listeners quando o novo valor é diferente do atual (!=). Para objetos mutáveis cujo estado interno mudou sem substituir a referência, chame refresh para forçar uma notificação.

Isolate safety: like the rest of Dart, an Observable is confined to the isolate that created it. Writing to it from a different isolate (e.g. via a raw Isolate.spawn, not compute/Isolate.run which copy data instead of sharing references) does not work — there is no cross-isolate synchronization here, by design; use SendPort/ReceivePort or compute to move data between isolates and write to the observable back on its own isolate.

Segurança entre isolates: como o restante do Dart, um Observable é confinado ao isolate que o criou. Escrever nele a partir de um isolate diferente (ex.: via Isolate.spawn bruto, não compute/ Isolate.run, que copiam dados em vez de compartilhar referências) não funciona — não há sincronização entre isolates aqui, por design; use SendPort/ReceivePort ou compute para mover dados entre isolates e escreva no observável de volta no seu próprio isolate.

Example / Exemplo:

final count = 0.obs;
Observer(() => Text('${count.value}'));
count.value++;
Implemented types
Implementers
Available extensions

Constructors

Observable(T initialValue, {String? name, bool equals(T a, T b)?})
Creates an observable holding initialValue. An optional name is used in debug logs and warnings; when omitted, a short hash-based label is used instead.

Properties

hashCode int
The hash code for this object.
no setterinherited
hasListeners bool
Whether this observable currently has at least one listener attached (an Observer tracking it, or a manual listen/addListener call).
no setter
isClosed bool
Whether close has already been called on this observable.
no setter
previousValue → T?
The value this observable held immediately before its most recent notified change, or null if it has never changed since creation. Only updated by an actual value change (the value setter when the new value differs); refresh does not touch it, since the value itself did not change.
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
value ↔ T
The current value of the object.
getter/setter pairoverride-getter

Methods

addListener(VoidCallback listener) → void
Register a closure to be called when the object notifies its listeners.
override
call([T? newValue]) → T
Shorthand for assigning newValue, mirroring observable(newValue).
close() → void
Disposes this observable: removes all listeners and marks it isClosed. Subsequent writes are ignored with a debug warning.
listen(ObserverCallback<T> callback, {bool immediate = false, bool when(T value)?}) ObservableSubscription
Subscribes callback to future value changes without going through an Observer widget. If immediate is true, callback also fires once immediately with the current value. If this observable is already closed, returns an already-canceled (inert) subscription and never registers a listener — immediate still fires once, since reading the last value is harmless.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
notifyListeners() → void
Notifies every current listener. Exposed for subclasses (e.g. collections) that mutate internal state through means other than the value setter.
peek() → T
Reads value without registering it as a dependency of whatever Observer/Computed/Effect is currently tracking (if any). Sugar for untracked(() => observable.value).
persistWith(ObservableStore<T> store) Disposer

Available on Observable<T>, provided by the ObservableStoreBinding extension

Restores this Observable's value from store immediately (if store has a persisted value — i.e. store.read() returns non-null), then persists every subsequent value change back to store via store.write. Returns a Disposer that stops the persistence (call it, typically, from ObserverStateMixin.autoDispose or your own dispose()) without touching the Observable itself — it keeps working as a normal, unpersisted Observable afterward.
refresh() → void
Forces listener notification without changing value. Use this after mutating a referenced object's internal state in place.
removeListener(VoidCallback listener) → void
Remove a previously registered closure from the list of closures that the object notifies.
override
select<R>(R selector(T value), {String? name}) Computed<R>

Available on Observable<T>, provided by the ObservableSelectExtension extension

Returns a Computed that recomputes to selector(value) whenever this Observable changes, exactly equivalent to writing Computed(() => selector(observable.value), name: name) by hand.
setValue(T newValue) → void
Assigns newValue, equivalent to value = newValue. Provided as a regular method (rather than only the value = setter) for call sites that need a tear-off (e.g. passing it directly as an onChanged callback), and to unambiguously assign null to an Observable<T?> — unlike call, which treats a null argument as "no argument".
toString() String
A string representation of this object.
inherited
watch(BuildContext context) → T

Available on Observable<T>, provided by the WatchExtension extension

Reads the current value and subscribes context's Element: when this observable changes, only that element rebuilds — Observer semantics at the granularity of the calling widget.
withHistory({int limit = 100}) ObservableHistory<T>

Available on Observable<T>, provided by the ObservableHistoryExtension extension

Returns a new ObservableHistory tracking this Observable, keeping at most limit recorded values. The caller owns the result and is responsible for calling ObservableHistory.dispose on it when done — mirrors select's ownership contract.

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Methods

batch(void action()) → void
Runs action, coalescing every Observable/collection write inside it so each distinct changed one notifies its manual listen/ever listeners exactly once, after action returns — writes still apply immediately, only the notification is deferred. Nested calls are supported (only the outermost flushes); if action throws, the pending queue is discarded and the exception propagates. Only affects manual subscriptions — an Observer already coalesces rebuilds per frame on its own.