일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- appstroe connect guideline
- Flutter
- flutter_dotenv
- exception caught by image resource service
- app stroe connect guideline
- 플러터
- app completeness
- app store connect guideline
- Guideline 5.1.1
- tflite_flutter
- .dio
- exception
- 에러
- undefined name
- withopacity
- guideline 4.3(a)
- AI
- guideline 1.5
- information needed
- flutter doctor -v
- get_it
- pub.dev
- dart sdk version upgrade
- 채팅 메시지 정렬
- infinity or nan toint
- flutter_secure_storage
- providernotfoundexception
- appstore connect guideline
- youtube_player_flutter
- permissiondeniedexception
Archives
- Today
- Total
min_chan님의 블로그
[pub.dev] - get_it 본문
get_it이란?
- Flutter로 프로젝트를 진행하다 보면 앱의 규모가 커지고 위젯에서 직접 객체를 관리하는 구조로는 유지 보수나 테스트가 어려워지는 시점이 오기 시작한다. 이때 get_it의 간단하면서도 강력한 서비스 로케이터 패턴으로 문제를 해결할 수 있다.
- Flutter는 InheritedWidget, Provider, Riverpod등 다양한 상태관리 솔루션을 제공한다. 하지만 get_it은 상태 관리 도구 보다는 객체 접근 방식을 개선해주는 서비스 로케이터다.
- BuildContext 없이 객체에 접근 가능
- UI 트리와 분리된 비즈니스 로직 작성
- 테스트 용이: 실제 객체와 mock 객체를 쉽게 교체 가능
- Clean Architecture와의 궁합이 좋음
get_it 사용법
1. 패키지 설치
- 터미널에서 pub add 명령어를 실행해 패키지 설치
2. 객체 등록 (앱 시작 시)
final getIt = GetIt.instance;
void setupLocator() {
getIt.registerSingleton<AppModel>(AppModel());
// 전역 변수를 좋아하지 않는다면, 이런 식으로도 작성할 수 있다
getIt.registerLazySingleton<ApiService>(() => ApiServiceImpl());
}
3. 객체 사용
- 그 후 AppModel은 클래스는 다음과 같이 어디서든 사용할 수 있다.
ElevatedButton(
// AppModel에 업데이트 메서드가 있는 경우
onPressed: getIt<AppModel>().update,
child: Text('업데이트'),
);
4. get_it을 활용한 테스팅
- 단위 테스트(Unit Tests)
- 테스트할 객체를 만들 때, 그 객체가 필요로 하는 객체들을 생성자(constructor)를 통해 다음과 같이 전달
GetIt getIt = GetIt.instance;
class UserManager {
AppModel appModel;
DbService dbService;
UserManager({AppModel? appModel, DbService? dbService}) {
this.appModel = appModel ?? getIt.get<AppModel>();
this.dbService = dbService ?? getIt.get<DbService>();
}
}
이 방법을 사용하면 AppModel이나 dbService 같은 의존성들을 실제 앱 코드에서는 직접 전달할 필요가 없고, 단위 테스트에서는 필요할 경우(혹은 mock 버전을) 전달할 수 있다.
- 통합 테스트 (Integration Tests)
- 어떤 서비스의 mock 버전이 있다면, 플래그 하나만으로 실제 서비스와 mock을 쉽게 전환할 수 있다.
if (testing) {
getIt.registerSingleton<AppModel>(AppModelMock());
} else {
getIt.registerSingleton<AppModel>(AppModelImplementation());
}
'pub.dev' 카테고리의 다른 글
[pub.dev] - intl (0) | 2025.03.17 |
---|---|
[pub.dev] - dio (0) | 2025.03.14 |
[pub.dev] - http (0) | 2025.03.13 |
[pub.dev] - flutter_secure_storage (0) | 2025.03.05 |
[pub.dev] - flutter_dotenv (0) | 2025.02.27 |