# 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.

```dart
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.&#x20;

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

```dart
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.&#x20;

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.


---

# 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/transitions/guard-conditions.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.
