current property

State<T>? current

Returns the current state of this machine, or null.

Implementation

State<T>? get current => _current;
void current=(Object? state)

Sets this machine to the given state, either specified with a State object, one of its identifiers, or null to remove the active state.

Throws an ArgumentError, if the state is unknown or from a different Machine.

Triggers a BeforeTransitionEvent event before the transition starts. This gives listeners the opportunity to observe the transitions and possibly abort before it starts.

Triggers a AfterTransitionEvent event after the transition completes. Errors during the transition phase are collected and included in the event. Handlers can inspect and clear the errors. If any errors remain, a single TransitionError is rethrown at the end of the state change.

Implementation

set current(/*State<T>|T|Null*/ Object? state) {
  // Find and validate the target state.
  final target = state is State<T>
      ? state
      : state is T
          ? this[state]
          : state == null
              ? null
              : throw ArgumentError.value(state, 'state', 'Invalid state');
  if (target != null && target.machine != this) {
    throw ArgumentError.value(state, 'state', 'Invalid machine');
  }
  // Notify listeners about the upcoming transition. Check if any of the
  // listeners wish to abort the transition.
  final source = _current;
  if (_beforeTransitionController.hasListener) {
    final transitionEvent = BeforeTransitionEvent<T>(this, source, target);
    _beforeTransitionController.add(transitionEvent);
    if (transitionEvent.isAborted) {
      return;
    }
  }
  // Deactivate the source state.
  final errors = <Object>[];
  if (source != null) {
    for (final transition in source.transitions) {
      try {
        transition.deactivate();
      } catch (error) {
        errors.add(error);
      }
    }
  }
  // Switch to the target state.
  _current = target;
  // Activate the target state.
  if (target != null) {
    for (final transition in target.transitions) {
      try {
        transition.activate();
      } catch (error) {
        errors.add(error);
      }
    }
  }
  // Notify listeners about the completed transition.
  if (_afterTransitionController.hasListener) {
    _afterTransitionController
        .add(AfterTransitionEvent<T>(this, source, target, errors));
  }
  // Rethrow any remaining transition errors at the end.
  if (errors.isNotEmpty) {
    throw TransitionError<T>(this, source, target, errors);
  }
}