유한 상태 기계를 구현하기 위한 플러터/다트 라이브러리로, 개발자가 쉽게 합법적인 상태 전이를 정의하고 관리할 수 있도록 합니다. 명확한 이벤트 기반 상태 변경을 제공하며, 상태 진입, 탈출 및 전이 이벤트를 듣는 것을 지원합니다. 상태 일관성과 예측 가능한 동작이 중요한 복잡한 워크플로우 모델링에 적합합니다. 패키지는 플랫폼 독립적이며 모든 주요 플러터 플랫폼을 지원합니다. 상태 로직을 UI 컴포넌트에서 분리함으로써 깔끔하고 유지보수 쉬운 코드를 촉진합니다.
사용 사례
다단계 사용자 흐름 관리
응용 프로그램 수명 주기 상태 모델링
비동기 워크플로 처리
폼 검증 상태 기계 구현
비즈니스 규칙 준수 강제
주요 기능
이벤트 기반 상태 전이
상태 진입/출구/전이용 콜백
형 안전한 상태 정의
중첩 및 계층적 상태 지원
확장 가능하고 테스트 가능한 설계
적합한 대상
복잡한 상태 기반 앱을 개발하는 개발자
결정론적 상태 관리가 필요한 팀
상태 변경의 감사가 필요한 프로젝트
엄격한 워크플로우 규칙을 가진 애플리케이션
고려 사항
초보자를 위한 학습 곡선이 더 가파릅니다
상태 그래프에 대한 신중한 계획이 필요합니다
간단한 상태 시나리오에서 오버헤드를 유발할 수 있습니다
제한된 내장 UI 통합
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
Dart State Machine
Easily create a finite state machine and define legal state transitions. Listen to state entrances, departures, and transitions.
Getting Started
Import the state_machine package:
import'package:state_machine/state_machine.dart';
Create a Machine
Once created, the StateMachine will be used to create states and state transitions.
StateMachine light = newStateMachine('light');
Define a Set of States
Use the machine to create all required states. A string name is required for ease of debugging.
State isOn = light.newState('on');
State isOff = light.newState('off');
It's recommended that states be named in the format "is[State]".
This may seem strange at first, but it has two main benefits:
It helps differentiate states from transitions, which can be confusing
since many words in English are the same as a verb and an adjective
("open" or "secure", for example).
It reads better when calling the state to determine if it's active,
as will be demonstrated later.
Define the Legal State Transitions
By defining legal state transitions, you can prevent certain actions based on the current state of the machine.
Defining a state transition requires a name (again for ease of debugging), a list of valid "from" states, and
the state to transition the machine to.
The StateTransition class exposes a listen() method that allows you to listen to the transition and receive an
event every time the transition executes.
turnOn.listen((StateChange change) {
print('Light transitioned from ${change.from.name} to ${change.to.name}');
});
light.start(isOff);
turnOn(); // "Light transitioned from off to on"
Passing Data with a State Transition
State transitions accept an optional payload in case you need to pass data along to listeners.
turnOn.listen((StateChange change) {
print('Light turned on. Wattage: ${change.payload}');
});
light.start(isOff);
turnOn('15w'); // "Light turned on. Wattage: 15w"
Listening for State Entrances and Departures
The State class exposes two streams so that you can listen for the state being entered and the state being left.
The State class exposes a static instance State.any that can be used as a wildcard when defining a state transition.
StateMachine machine = newStateMachine('machine');
State isFailed = machine.newState('failed');
// This transition will be valid regardless of which state the machine is in.StateTransition fail = machine.newStateTransition('fail', [State.any], isFailed);
Illegal State Transitions
When you create state transitions, you must define the list of valid "from" states. The machine must be in one of these
states in order to execute the transition. If that's not the case, an IllegalStateTransition exception will be thrown.
// Consider a door with the following states and transitions.StateMachine door = newStateMachine('door');
State isOpen = door.newState('open');
State isClosed = door.newState('closed');
State isLocked = door.newState('locked');
StateTransition open = door.newStateTransition('open', [isClosed], isOpen);
StateTransition close = door.newStateTransition('close', [isOpen], isClosed);
StateTransition lock = door.newStateTransition('lock', [isClosed], isLocked);
StateTransition unlock = door.newStateTransition('unlock', [isLocked], isClosed);
// Let's transition the door from open, to closed, to locked.
door.start(isOpen);
close();
lock();
// In order to open the door, we must first unlock it.// If we try to open it first, an exception will be thrown.open(); // throws IllegalStateTransition
Canceling State Transitions
State machines have a set of legal state transitions that are set in stone and provide the required structure.
But, there may be scenarios where a state transition may or may not be desirable based on additional logic.
To handle this, state transitions support cancellation conditions.
// Consider two state machines - a person and a door.// The door can be locked or unlocked and the person// can be with or without a key.StateMachine door = newStateMachine('door');
State isLocked = door.newState('locked');
State isUnlocked = door.newState('unlocked');
StateTransition unlock = door.newStateTransition('unlock', [isLocked], isUnlocked);
StateMachine person = newStateMachine('person');
State isWithKey = person.newState('withKey');
State isWithoutKey = person.newState('withoutKey');
StateTransition obtainKey = person.newStateTransition('obtainKey', [isWithoutKey], isWithKey);
door.start(isLocked);
person.start(isWithoutKey);
// Add a cancellation condition for unlocking the door:// If the person is without a key, cancel the unlock transition.
unlock.cancelIf((StateChange change) => isWithoutKey());
unlock(); // false (canceled)isUnlocked(); // falseobtainKey();
unlock(); // true (not canceled)isUnlocked(); // true
Example
To run the example:
dart pub global activate webdev
webdev serve example:8080
open http://localhost:8080/