Programming Framework/Flutter
[Flutter] GetIt 패키지를 이용한 Service Locator 전역 상태 관리
HoZang
2024. 5. 25. 23:29
[Flutter] GetIt 패키지를 이용한 Service Locator 전역 상태 관리
class UserService extends ChangeNotifier {
UserService();
User? get user => _user;
User? _user;
set user(User? user) {
_user = user;
// 값 변경을 알려주는 notifyListeners 추가.
notifyListeners();
}
}
void main() {
// GetIt을 이용해서 전역상태 관리를 할 객체 Service Locator 등록
GetIt.I.registerSingleton<UserService>(UserService());
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _userService = GetIt.I<UserService>();
@override
void initState() {
super.initState();
// statefull widget의 상태를 초기화 할 때
// service locator listener에 현재 widget 상태변경 알림 추가
// ChangeNotifier를 상속한 service locator의 notifyListeners가 동작할 때
// 현재 widget의 state도 업데이트 된다.
_userService.addListener(() => setState(() {}));
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ServiceLocatorState',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
useMaterial3: true,
fontFamily: "NanumBarunGothic"
),
home: HomeScreen(title: 'Z Talk', products: products)
);
}
}