set<T> method
Updates a state value of type T in the container.
This method provides a type-safe way to modify a previously registered
state value. The update is performed using a functional approach where the
current state is passed to the updater function, which returns the new
state value.
T The type of the state value to update.
updater A function that receives the current state value and returns
a new state value. This function should be pure and not cause side
effects.
name An optional name identifier for the state value. Used when multiple
state values of the same type need to be distinguished.
addToEventStream Whether to emit a SetEvent to the event stream
when the stream is open. Defaults to true. Set to false to update
state silently without notifying event stream listeners.
The state is only updated if the new value is not identical to the current value (using identical comparison). If an update occurs, widgets that watch this state will be automatically rebuilt.
Throws an ArgumentError if the state of type T with the given name
has not been registered.
Implementation
@override
@visibleForTesting
@protected
void set<T>(T Function(T current) updater,
{String? name, bool addToEventStream = true}) {
if (!_hasKey<T>(name)) {
throw ArgumentError(
'Piece of state of type "$T" ${name != null ? 'and name "$name" ' : '(no name) '}not found. You must register it in the constructor of your Hako class before setting it to a new value.',
);
}
final previous = _stateMap[(T, name)] as T;
final state = updater(previous);
if (!identical(previous, state)) {
_stateMap[(T, name)] = state;
if (addToEventStream) {
onEvent(SetEvent<T>(name: name, previous, state));
}
_onSetCalled?.call();
}
}