when method

TransitionHandlerWhenBuilder when(
  1. FutureOr<bool> condition(
    1. TransitionContext transCtx
    ),
  2. void buildTrueHandler(
    1. TransitionHandlerBuilder
    ), {
  3. String? label,
})

Indicates that a transition action should conditionally occur.

When the transition occurs, condition will be evaluated. If true is returned, the transition actions defined by the buildTrueHandler callback will be invoked.

This method returns a builder that can be used to define additional conditions, including an otherwise callback that can be used to define the transition behavior when none of the conditions evaluate to true.

var state1 = StateKey('s1');
var builder = StateTreeBuilder(initialState: state1);

builder.state(state1, (b) {
  b.onEnter((b) {
    // Conditionally run an action when the state is entered.
    b.when(
      (transCtx) => false,
      (b) => b.run((transCtx) => print('Condition 1 is true'))
    ).when(
      (transCtx) => true,
      (b) => b.run((transCtx) => print('Condition 2 is true'))
    ).otherwise(
      (b) => b.run((transCtx) => print('No conditions are true'))
    );
  });
});

The condition can be labeled when formatting a state tree by providing a label.

Implementation

TransitionHandlerWhenBuilder when(
  FutureOr<bool> Function(TransitionContext transCtx) condition,
  void Function(TransitionHandlerBuilder) buildTrueHandler, {
  String? label,
}) {
  var trueBuilder = TransitionHandlerBuilder._(_forState);
  buildTrueHandler(trueBuilder);
  var conditions = [_TransitionCondition(condition, trueBuilder._handler!, label)];
  _handler = _TransitionWhenDescriptor(conditions, label);
  return TransitionHandlerWhenBuilder(_forState, conditions);
}