# States

A state represents a stage in an FSM's life cycle.

An FSM will have an initial state just like you. We can describe your life with an FSM.

Twinkle -> Gestation -> Baby -> Teenager -> Adult ->  Dead

Each of the above stages in your life can be modeled as a State in an FSM.

Let's have a look at that.

```
void _createMachine() {
  machine = StateMachine.create((g) => g
    ..initialState<Twinkle>()
    ..state<Twinkle>((b) {})
    ..state<Gestation>((b) {})
    ..state<Baby>((b) {})
    ..state<Teenager>((b) {})
    ..state<Adult>((b) {})
    ..state<Dead>((b) {}));
}
```

We have now definititively identified all of the stages of your life including your 'initialState' of 'Twinkle'.

We can also model the events that cause you to move from one stage of your life to the next.

```
  machine = StateMachine.create((g) => g
    ..initialState<Twinkle>()
    ..state<Twinkle>((b) => b
      ..on<Conception, Gestation>())
    ..state<Gestation>((b) => b
      ..on<Born, Baby>())
    ..state<Baby>((b) => b
      ..on<Puberty, Teenager>())
    ..state<Teenager>((b) => b
      ..on<GetDrunk, Adult>())
    ..state<Adult>((b) => b
      ..on<Death, Dead>())
    ..state<Dead>((b) {}));
```

We have now added events that cause the transitions from one stage of your life to the next.

You start out as a 'Twinkle' in the eye of your father.  Then there is a rather messy 'Conception' event, where you are conceived which takes you into the 'Gestation' state.

So lets conceive you.

```
statemachine.applyEvent(Conception());
```

The transition call sends an event to the state machine, as we start out in the 'Twinkle' state the 'Conception' event is matched resulting in the transition to the 'Gestation' state.

## Initial State

You may define the initial state for the top level state and each [nested](/states/nested-states.md) substate using the 'initialState' method.

If you don't define an 'initialState' then the first state in the substate will be used as the initial state.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://fsm2.onepub.dev/states.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
