728x90
반응형
안녕하세요 이번 글에서는 데이터를 핸드폰에 저장하기 위한 sqlite를 사용해 보겠습니다.
프로젝트 구조
pubspec.yaml
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
drift: ^2.2.0 # sqlite 를 사용하기 위한 라이브러리
sqlite3_flutter_libs: ^0.5.0 #DB
path_provider: ^2.0.0 # 파일 시스템에서 일반적으로 사용되는 위치를 찾기 위한 Flutter 플러그인
path: ^1.8.2
get_it: ^7.2.0 # Db를 조작하기 위한 플러그인
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
build_runner: ^2.2.1 # 외부에서 Dart 코드를 사용하여 파일을 생성하는 구체적인 방법을 제공
drift_dev: ^2.2.0+1v
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
디펜던시를 위처럼 설정하여 줍니다.
member.dart
class Member extends Table{
// id 자동생성
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text()();
DateTimeColumn get date => dateTime()();
}
테스트 용으로 사용할 model을 만들어 줍시다.
drift_database.dart
import 'dart:io';
import 'package:database/model/member.dart';
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as P;
// 여기는 자동생성 할 파일
part 'drift_database.g.dart';
@DriftDatabase(
tables: [
Member,
],
)
class LocalDatabase extends _$LocalDatabase{
LocalDatabase() : super(_openConnection());
@override
int get schemaVersion => 1;
}
LazyDatabase _openConnection(){
return LazyDatabase(() async{
final dbFolder = await getApplicationDocumentsDirectory();// 앱 전용으로 사용할 수 있는 폴더
final file = File(P.join(dbFolder.path,'db.sqlite')); // 저장할 db 파일 생성
return NativeDatabase(file);
});
}
데이터베이스 설정을 위해 drift_database.dart 파일을 만들어 줍시다.
part 'drift_database.g.dart';
해당 부분에서 에러가 나지만 일단은 그냥 넘어가 주세요
완성이 되었으면 터미널을 켜고
flutter pub run build_runner build
명령어를 실행시켜 줍시다 그러면 drift_database.g.dart 파일이 생성된 것을 확인할 수 있습니다.
다음 글에서 기본적은 CRUD를 해보도록 하겠습니다.
728x90
반응형
'Flutter' 카테고리의 다른 글
[ Flutter ] sqlite & drift 사용하기 - 3편 (0) | 2022.12.21 |
---|---|
[ Flutter ] sqlite & drift 사용하기 - 2편 (0) | 2022.12.18 |
[ Flutter ] 배경 데코레이션 & 이미지 터치 만들기 (0) | 2022.11.06 |
[ Flutter ] Slider 사용하기 (0) | 2022.11.06 |
[ Flutter ] Future 함수 사용하기 (0) | 2022.11.06 |