Dart Shared_preferences

강정우·7일 전
0

Flutter&Dart

목록 보기
97/97
post-thumbnail

Shared_preferences

엄밀히 말하자면 Sqflite, Hive, Drift 와 같은 DB 는 아니다.
key-value 형태로 어떠한 값들을 저장하는 것이 가능하다.
다만, 간단한 설정값 저장에는 Shared_preferences 사용하면 된다.

옆에 보면 shared_prefs 에 단 한개의 파일만 존재하기 때문에 생성자를 여러번 사용하게 되면 시멘틱한 코드가 되지 못한다.
따라서 우리는 딱 하나의 인스턴스만 존재하는 싱글턴 init() 을 만들어주면 된다.

하지만 위와같이 사용을 한다면 반드시 에러가 난다.

main(){
	final preference = AppSharedPreference();
    preference.setCount();
}

를 하면 아직 초기화가 안 된 상황이기 때문에 에러가 나게 되어있다.
따라서 우리는 App 이 뜰때 미리 싱글톤 애들을 생성해서 넣어주면 된다.

#main.dart
void main() async {
  // App 이 뜨기 전에 필요한 것들을 여기에 넣어줘야함.

  final bindings = WidgetsFlutterBinding.ensureInitialized();
  FlutterNativeSplash.preserve(widgetsBinding: bindings);
  await EasyLocalization.ensureInitialized();
  await AppPreferences.init();
  // sqflite
  timeago.setLocaleMessages('ko', timeago.KoMessages());

  runApp(EasyLocalization(
      supportedLocales: const [Locale('en'), Locale('ko')],
      fallbackLocale: const Locale('en'),
      path: 'assets/translations',
      useOnlyLangCode: true,
      child: const App()));
}

그리고 이제 then 대신 main 단에서 객체를 생성했다면 우리는 이제 해당 싱글톤 shared_preference 를 사용할 때

AppshearedPreference.instance.setCount(0);

으로 사용해야하는데 잘 생각해보면 굳이 instace 키워드가 매번 작성되어야할까를 의심해봐야한다.
그렇다면 우리는 이제 해당 class 에서는 다음과 같이 코드를 작성하면 된다.

import 'package:shared_preferences/shared_preferences.dart';

class AppSharedPreference {
  AppSharedPreference._();
  static AppSharedPreference instace = AppSharedPreference._();

  // 그리고 key 값을 String 만으로 구별하면 에러가 나기 때문에
  static const keyCount = "keyCount";
  static const keyLaunchCount = "keyLaunchCount";

  late SharedPreferences _preferences;

  // init 함수를 수동으로 호출하기 귀찮으니까
  // 보통 main 함수에서 초기화를 먼저 시켜준다.
  // void init() async {
  //   _preferences = await SharedPreferences.getInstance();
  // }
  static init() async {
    instace._preferences = await SharedPreferences.getInstance();
  }

  static void setCount(int count) {
    instace._preferences.setInt(keyCount, count);
  }

  /// null 일땐, -99999999 값이 들어옵니다.
  static int getCount() {
    return instace._preferences.getInt(keyCount) ?? -99999999;
  }
}
profile
智(지)! 德(덕)! 體(체)!

0개의 댓글