플러터 Persistence (disk key-value, file, SQLite)

LeeWonjin·2024년 4월 27일
0

플러터

목록 보기
10/15

key-value 데이터

shared_preferences패키지를 사용하면

  • 하나의 코드로
  • 여러 플랫폼의 on-device key-value 데이터를 관리할 수 있다.
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,
});

지원하는 타입은 원시타입들.

  • int, double, bool, String
  • List<String>

주의할 점 : 이게 기기에 남아있을거라고 항상 장담할 수 없으니, 없으면 동작안하는 중요한건 key-value 데이터로 관리하지 마라.

파일

앱의 데이터가 저장되는 곳은 두 가지로 분류한다.

  • 임시 디렉토리 : 언제든 지워질 수 있다.
  • 문서 디렉토리 (Documents directory) : 앱이 지워지기 전까지 남아있다

여기서는 문서 디렉토리를 중점으로 보자 (그걸 주로 쓸테니까)
아래 두 가지의 조합으로 파일 읽고 쓰기를 할 수 있다.

  • dart:io에서 제공하는 File클래스
  • 경로를 구하기 위한 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;
}

SQLite

key-value 데이터인데 대용량일 때 빠르고 쉽게 처리하기 위해 쓴다.
쿼리문도 쓸 수 있다.

flutter pub add sqflite path

https://docs.flutter.dev/cookbook/persistence/sqlite

그냥 로컬 DBMS고, 플러터쪽에서는 클래스 모델 만들어서 접근한다고 생각하면 된다.

  • SQLite쪽에 테이블 만들고
  • 클래스로 엔티티의 모델을 만들어두고
    • 이 모델로 테이블에 레코드 추가, 업데이트, 삭제

별건 없다.

profile
노는게 제일 좋습니다.

0개의 댓글

관련 채용 정보