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 optionalnameis 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
nullif 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, mirroringobservable(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
callbackto future value changes without going through an Observer widget. Ifimmediateistrue,callbackalso fires once immediately with the current value. If this observable is already closed, returns an already-canceled (inert) subscription and never registers a listener —immediatestill 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/Effectis currently tracking (if any). Sugar foruntracked(() => observable.value). -
persistWith(
ObservableStore< T> store) → Disposer -
Available on Observable<
Restores this Observable's value fromT> , provided by the ObservableStoreBinding extensionstoreimmediately (ifstorehas a persisted value — i.e.store.read()returns non-null), then persists every subsequent value change back tostoreviastore.write. Returns a Disposer that stops the persistence (call it, typically, fromObserverStateMixin.autoDisposeor your owndispose()) 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<
Returns a Computed that recomputes toT> , provided by the ObservableSelectExtension extensionselector(value)whenever this Observable changes, exactly equivalent to writingComputed(() => selector(observable.value), name: name)by hand. -
setValue(
T newValue) → void -
Assigns
newValue, equivalent tovalue = newValue. Provided as a regular method (rather than only thevalue =setter) for call sites that need a tear-off (e.g. passing it directly as anonChangedcallback), and to unambiguously assignnullto anObservable<T?>— unlike call, which treats anullargument as "no argument". -
toString(
) → String -
A string representation of this object.
inherited
-
watch(
BuildContext context) → T -
Available on Observable<
Reads the current value and subscribesT> , provided by the WatchExtension extensioncontext's Element: when this observable changes, only that element rebuilds —Observersemantics at the granularity of the calling widget. -
withHistory(
{int limit = 100}) → ObservableHistory< T> -
Available on Observable<
Returns a new ObservableHistory tracking this Observable, keeping at mostT> , provided by the ObservableHistoryExtension extensionlimitrecorded values. The caller owns the result and is responsible for calling ObservableHistory.dispose on it when done — mirrorsselect'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/everlisteners exactly once, afteractionreturns — writes still apply immediately, only the notification is deferred. Nested calls are supported (only the outermost flushes); ifactionthrows, the pending queue is discarded and the exception propagates. Only affects manual subscriptions — an Observer already coalesces rebuilds per frame on its own.