Guard conditions

FSM2 supports guard conditions on transitions which only allow an event to trigger a transition if some condition is met.

Guard conditions allow you to declare (via the on builder) the same Event multiple times from a single State. When registering multiple transitions with the same Event type only a single event (the default transition) may have an empty guard condition and it MUST be the last event added to the state.

If a State has multiple transitions for the same event, then the transitions will be evaluated in the order they are declared. The first transition whose guard condition returns true will be triggered. No further guard conditions will be evaluated. A transition without a Guard Conditions (the default transition) always evaluates to true.

import 'package:fsm2/fsm2.dart';

void main() {
  var temperature = 0;
  final machine = StateMachine.create((g) => g
    ..initialState(Solid())
    ..state<Solid>((b) => b
      ..on<OnHeat, Liquid>(condition: temperature + e.deltaDegrees > 0)
      ..on<OnHeat, Boiling>(condition: temperature + e.deltaDegrees > 100)
      ..on<OnHeat, Solid>()
 ));

You can see from the above example that the OnHeat Event contains a field deltaDegrees. It is often useful to pass arguments to your events which can then be applied to the State.

To pass a value into an event: (your event must take a named argument deltaDegrees).

machine.applyEvent(OnHeat(deltaDegrees: 25));

When machine.applyEvent is called, and the FSM is in the Solid state, then the FSM will evaluate each onHeat transition in the order that they are declared.

The first transition whose condition evaluates to true will be applied. No further transitions will be considered.

Default Transition

The above example contains three onHeat transitions, the last one does not have a guard condition. This is considered the default transition. If all other transitions fail their condition test, then the default transition will be triggered.

You do not have to have a default transition. If you don't have a default transition and all conditions fail then no transition is triggered and the State of the machine does not change.

Last updated