개발/Flutter

[Flutter] SharedPreferences

laladev 2024. 8. 11. 07:44

SharedPreferences

가볍게 사용하기 좋은 로컬 저장소 라이브러리이다.

Key-Value 형태로 데이터를 저장 및 불러올 수 있다.

데이터 타입별로 read & write 함수가 있다.

설치는 아래와 같이 실행

flutter pub add shared_preferences

 

 

Code Template

// 초기화
final SharedPreferences prefs = await SharedPreferences.getInstance();


// Write
await prefs.setInt('counter', 10);
await prefs.setBool('repeat', true);
await prefs.setDouble('decimal', 1.5);
await prefs.setString('action', 'Start');
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);


// Read (키가 존재하지 않으면 null 을 리턴)
final int? counter = prefs.getInt('counter');
final bool? repeat = prefs.getBool('repeat');
final double? decimal = prefs.getDouble('decimal');
final String? action = prefs.getString('action');
final List<String>? items = prefs.getStringList('items');


// Remove
await prefs.remove('counter');
prefs.clear(); // 모두 삭제

 

 

참고

https://pub.dev/packages/shared_preferences