state_machine library

A simple, typed finite state machine library.

State machines are created by defining a set of states and a set of legal state transitions.

These machines can be used inline, or they can be easily wrapped in a class to provide a more formal API by directly exposing the States and StateTransitions directly.

Simple usage:

StateMachine door = new StateMachine('door');
State isOpen = door.newState('open');
State isClosed = door.newState('closed');
StateTransition open = door.newStateTransition('open', [isClosed], isOpen);
StateTransition close = door.newStateTransition('close', [isOpen], isClosed);

isClosed(); // true

Wrapping in a class:

class Door {
  State isOpen;
  State isClosed;

  StateTransition open;
  StateTransition close;

  StateMachine _machine;

  Door() {
    _machine = new StateMachine('door');
    isOpen = _machine.newState('open');
    isClosed = _machine.newState('closed');
    open = _machine.newStateTransition('open', [isClosed], isOpen);
    close = _machine.newStateTransition('close', [isOpen], isClosed);

void main() {
  Door door = new Door();

  // Exposing the [State] and [StateTransition] objects
  // created a useful and understandable API for the Door
  // class without any extra work!
  door.isClosed(); // true


Represents a state that can be visited within a StateMachine instance.
Represents a change for a StateMachine instance from one state to another. If a payload was supplied when executing the transition, it will be available via payload.
A simple, typed finite state machine.
Represents a legal state transition for a StateMachine instance.

Exceptions / Errors

An exception that is thrown when attempting to create a new State or StateTransition for a StateMachine instance that has already been started.
An exception that is thrown when attempting to execute a state transition for a StateMachine instance when the machine is in a state that is not defined as a legal "from" state by the StateTransition instance.