Water Example

Example

A simple example showing the life cycle of H2O.

import 'package:fsm2/fsm2.dart';

void main() async {
  final machine = StateMachine.create((g) => g
    ..initialState<Solid>()
    ..state<Solid>((b) => b..on<OnMelted, Liquid>(sideEffect: () => print('Melted')))
    ..state<Liquid>((b) => b
      ..onEnter((s, e) => print('Entering ${s.runtimeType} State'))
      ..onExit((s, e) => print('Exiting ${s.runtimeType} State'))
      ..on<OnFroze, Solid>(sideEffect: (e) => print('Frozen'))
      ..on<OnVaporized, Gas>(sideEffect: (e) => print('Vaporized')))
    ..state<Gas>((b) => b..on<OnCondensed, Liquid>(
        sideEffect: (e) => print('Condensed')))
    ..onTransition((t) => print(
        'Recieved Event ${t.eventType} in State ${t.fromState.runtimeType} transitioning to State ${t.toState.runtimeType}')));

  /// static analysis of the state machine.
  /// only do this during testing.
  await machine.analyse();
  
  /// export the statemachine to a dot file so we can visualise it.
  await machine.export('test/test.gv');

  print(await machine.isInState<Solid>()); // TRUE

  machine.applyEvent(OnMelted());
  print(await machine.isInState<Liquid>()); // TRUE

  machine.applyEvent(OnFroze());
  print(await machine.isInState<Solid>()); // TRUE
}

class Solid extends State {}

class Liquid extends State {}

class Gas extends State {}

class OnMelted extends Event {}

class OnFroze extends Event {}

class OnVaporized extends Event {}

class OnCondensed extends Event {}

Last updated