Finite State Machines

FSM2 is a partial implementation of the UML2 State Machine.

State Machines allow you to model the behaviour of a system by specifying the sequence of states that a system can be in, as well as the events that cause the system to move between states.

In the above FSM for Water we can see water has three states and we have modelled four events that causes Water to transition from one state to another.

FSM2 uses a builder model to create a state machine with support for both static and dynamic transitions.

Help support FSM2 by supporting OnePub, the private Dart repository.

OnePub allows you to privately share Dart packages across your Team and with your customers.

Try it for free and publish your first private package in seconds.

Publish a private package in five commands:

dart pub global activate onepub

onepub login

cd <my package>

onepub pub private

dart pub publish

To make your life easier FSM2 is able to generate a graphical visualisation of your FSM using the Graphwiz dot notation. This makes designing and debugging your state machine much easier.

Let's have a look at the code required to generate the above model:

var machine = StateMachine.create((g) => g
          ..state<Solid>((b) => b
            ..on<OnMelted, Liquid>(sideEffect: (e) => print('its melting')
            ..onEnter((s, e) => print('we are now solid')
            ..onExit((s, e) => print('bye bye solid existance'))
          ..state<Liquid>((b) => b
            ..on<OnFroze, Solid>(sideEffect: (e) => print('its getting cold'))
            ..on<OnVaporized, Gas>(sideEffect: (e) => print('its getting very hot'))
          ..state<Gas>((b) => b
            ..on<OnCondensed, Liquid>(sideEffect: (e) => print('move a little closer will you'))

Your state machine will have an initial state of Solid and to transition to an new state you send the state machine an event.


Once you have applied all events (which are processed asynchronously) you need to call:

await machine.complete;

The call will only return once all events have been processed. Until complete returns the StateMachine is considered to be in an indeterminate state.

To create a visualization of the state machine:


To view the FSM

apt install xdot
dotx test.gv


Credit goes where credit is due.

FSM2 started out life as a fork of FSM by Kirill Bubochkin https://github.com/ookami-kb/fsm which in turn was inspired by Tinder StateMachine library.

All of the good bits are his, all of the mistakes are mine :)

Last updated