Flutter 앱에서 Provider 없이 상태 관리 구현하기
배경
사내 모바일 앱을 Flutter로 리팩토링하면서 상태 관리 라이브러리를 선택해야 했다. Provider나 Bloc이 일반적이지만, 앱 규모가 크지 않아 InheritedWidget 기반으로 직접 구현했다.
구현
기본적인 구조는 InheritedWidget + ChangeNotifier 조합이다.
class AppState extends ChangeNotifier {
int _counter = 0;
int get counter => _counter;
void increment() {
_counter++;
notifyListeners();
}
}
class AppStateProvider extends InheritedNotifier<AppState> {
AppStateProvider({
Key? key,
required AppState state,
required Widget child,
}) : super(key: key, notifier: state, child: child);
static AppState of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<AppStateProvider>()!.notifier!;
}
}
위젯에서는 AppStateProvider.of(context)로 접근한다.
class CounterWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final state = AppStateProvider.of(context);
return Text('${state.counter}');
}
}
결과
- 외부 의존성 제거
- 코드 200줄 정도로 필요한 기능 모두 구현
- 팀원들이 Flutter 기본 개념만으로 이해 가능
다만 여러 상태를 관리하려면 보일러플레이트가 늘어난다. 앱이 커지면 Provider로 전환할 예정이지만, 지금은 이 정도로 충분했다.
참고
Flutter 공식 문서의 InheritedWidget 설명이 도움이 됐다. 상태 관리 라이브러리도 결국 이 위에 구축된 것이라는 점을 이해하게 됐다.