fsm2
Search
K
Comment on page

Simple Transitions

Simple transitions are declared using the 'on' builder.
import 'package:fsm2/fsm2.dart';
void main() {
final machine = StateMachine.create((g) => g
..initialState(Solid())
..state<Solid>((b) => b
..on<OnMelted, Liquid>())
);
The above examples creates a Finite State Machine (machine) which declares its initial state as being Solid and then declares a single transition Solid -> Liquid when the event OnMelted is applied to the FSM.
We can now write a unit test that validates our state machine when `machine.applyEvent(OnMelted())` is called.
import 'package:fsm2/fsm2.dart';
import 'package:test/test.dart';
test('test transition', () async {
/// build the state machine.
final machine = StateMachine.create((g) => g
..initialState(Solid())
..state<Solid>((b) => b
..on<OnMelted, Liquid>())
/// check its initial state
expect(machine.isInState<Solid>(), equals(true));
/// trigger the state change
await machine.applyEvent(OnMelted());
/// check we arrived in the expected state.
expect(machine.isInState<Liquid>(), equals(true));
});

Many transitions

A State can have any number of on transitions including multiple transitions for the same Event providing a guard conditions is used.
See the section on Guard Conditions for details on defining conditional transitions.