shared_preferences
패키지를 사용하면
flutter pub add shared_preferences
데이터 저장과 읽기, 지우기는 이렇게 한다.
setType메소드로 저장하면 각 아이템에 대해 getter가 생기는 컨셉.
final sp = await SharedPreferences.getInstance();
await sp.setInt('user_id', 1234); // set
final userId = sp.getInt('user_id'); // get
await sp.remove('user_id'); // delete
// 읽어온게 null이라 기본값으로 대체하고 싶다면?
// final userId = sp.getInt('user_id') ?? 0;
테스트는 이렇게 한다.
SharedPreferences.setMockInitialValues(<String, Object>{
'user_id': 1234,
});
지원하는 타입은 원시타입들.
주의할 점 : 이게 기기에 남아있을거라고 항상 장담할 수 없으니, 없으면 동작안하는 중요한건 key-value 데이터로 관리하지 마라.
앱의 데이터가 저장되는 곳은 두 가지로 분류한다.
여기서는 문서 디렉토리를 중점으로 보자 (그걸 주로 쓸테니까)
아래 두 가지의 조합으로 파일 읽고 쓰기를 할 수 있다.
path_provider
플러그인import 'package:path_provider/path_provider.dart';
Future<String> test() async {
// get local path
final dir = await getApplicationDocumentsDirectory();
final localPath = dir.path;
// get a local file
final File file = File('$path/something.txt');
// write to the file
file writeAsString('${123}hi');
// read from the file
final contents = await file.readAsString();
return contents;
}
key-value 데이터인데 대용량일 때 빠르고 쉽게 처리하기 위해 쓴다.
쿼리문도 쓸 수 있다.
flutter pub add sqflite path
https://docs.flutter.dev/cookbook/persistence/sqlite
그냥 로컬 DBMS고, 플러터쪽에서는 클래스 모델 만들어서 접근한다고 생각하면 된다.
별건 없다.