On this page
article
When
when is a decorator that conditionally executes the wrapped function or an alternative branch depending on a predicate.
When
What it is
when is a decorator that conditionally executes the wrapped function or an alternative branch depending on a predicate.
When to use it
- Feature flags that choose between implementations.
- Conditional execution without
if/elseat every call site. - Branching logic that you want to compose and reuse.
API reference
| |
Parameters
| Parameter | Type | Description |
|---|---|---|
condition | bool Function(...) | Decides whether to execute the wrapped function. |
otherwise | Future<R> Function(...)? | Optional branch executed when the condition is false. |
Examples
Basic example
| |
Real-world example
| |
Best practices
- Keep predicates fast and free of side effects.
- Ensure both branches return the same type
R.
Common pitfalls
- Async predicate timing: If the predicate depends on mutable state, branches may flip between calls.
- Branch exceptions: Exceptions in either branch propagate to the caller.