Skip to content
Ricardo Canastro edited this page Mar 6, 2022 · 2 revisions

Modeling statemachines might feel a bit abstract at times, having a way to visualize it and share with others is a major improvement on the developer experience.

Luckily for us, XState's visualizer is a wonderful tool, and we'll take advantage of it. Automata exposes exportToXStateViz that given a StateMachine instance creates a file with the necessary code for you to create your XState Viz.

Given the following state machine:

import 'package:automata/automata.dart';

final machine = StateMachine.create(
  (g) => g
    ..initial<Inactive>()
    ..state<Inactive>(
      builder: (g) => g..on<OnToggle, Active>()
    )
    ..state<Active>(
      builder: (g) => g..on<OnToggle, Inactive>()
    ),
  ),
  id: 'my_machine',
);

If you call:

await exportToXStateViz(machine);

It will create a file named my_machine.dart with the following content:

import { createMachine } from 'xstate';

const machine = createMachine(
  {
    id: 'my_machine',
    type: 'compound',
    initial: 'Inactive',
    states: {
      Inactive: {
        id: '{RootState, Inactive}',
        type: 'atomic',
        on: {
          OnToggle: {
            target: '#{RootState, Active}',
          },
        },
      },
      Active: {
        id: '{RootState, Active}',
        type: 'atomic',
        on: {
          OnToggle: {
            target: '#{RootState, Inactive}',
          },
        },
      },
    },
  },
  {
    guards: {
      canTransition: () => true,
    },
  }
);

Which you'll be able to copy to Stately's XState Visualizer.

Two notes about the generated content:

  • We create a dummy guard that is used on every transition that has a transition defined
  • We always use identifiers on our targets to be able to transition to parent compound state, see this issue
Clone this wiki locally