티스토리 뷰

[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)
    );
  }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함