[Flutter] drift - (2)drift_database.g.dart. 생성

Jinno·2023년 1월 13일
0

Flutter

목록 보기
11/19

1. database 폴더를 만들고, drift_database.dart 파일 생성

  • import 'package:drift/drift.dart'

2. part 'drift_database.g.dart'

  • '.g.'만 추가한 파일 part

3. @DriftDatabase decorator 설정

  • 만들었던 Table을 Type만 추가
  • TableNameA (TableNameA() X)

4. LocalDataBase Class 생성

  • 상속받는 _$LocalDataBase는 'drift_database.g.dart'에 drift 가 생성하게 됨
  • _$LocalDataBase는 underscore로 private 임에도 불러올 수 있는 이유는 import가 아닌 part로 불러왔기 때문임

5. _openConnection 함수 생성

  • getApplicationDocumentsDirectory() 함수로 해당 기기에서 DB를 저장하기 위해 사용할 수 있는 폴더 위치 리턴
  • File()을 사용하면, dart:io or dart:html import를 해야하는데, App에서는 dart:io 사용
  • File(p.join(dbFolder.path, 'db.sqlite')) 으로 해당 폴더의 경로를 가져오고, 그 경로에 'db.sqlite'라는 이름으로
  • NativeDatabase(file)로 파일 생성
import 'dart:io';
import 'package:drift/drift.dart';

import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';

part 'drift_database.g.dart';

(
  tables: [
    TableNameA,
    TableNameB,
  ],
)

class LocalDataBase extends _$LocalDataBase {
	LocalDataBase() : super(_openConnection())
}

LazyDatabase _openConnection() {
  return LazyDatabase(() async {
    //이 App 전용으로 사용할 수 있는 Folder 위치 리턴
    final dbFolder = await getApplicationDocumentsDirectory();
    final file = File(p.join(dbFolder.path, 'db.sqlite'));
    return NativeDatabase(file);
  });
}

profile
Innovation, 기록용

0개의 댓글