본문 바로가기

[Flutter] drift로 todo list 만들기 예제 - 1탄(with drift, SQLite)

ironwhale 2022. 3. 4.

시작하면서... 

이전에 Moor를 이용한 SQLite 사용법 포스팅을 한적이 있습니다. 

이후 Update와 Delete 부분에 대한 포스팅을 한다고 했는데 아직까지 못했네요 

지금은 Moor가 drift로 이름이 바뀐거 같더군요

이번에는 드리프트를 이용해서 간단한 할일리스트(to do list)를 만드는 예제를 만들어 보겠습니다. 

 

이전 포스팅

 

Flutter, Moor(SQLite ORM)을 사용한 CRUD 정리 - 1편 Create, Read - Flutter moor example, Dart ORM, Flutter database tool

외부 서버 등의 저장공간을 사용하지 않고 손쉽게(?) 휴대폰 내부 저장공간에 사용 할 수 있는 로컬 DB은 SQLite를 ORM 형식으로 사용할수 있게 해주는 Moor 패키지에 대해 예제를 프로젝트를 만들어

jh-industry.tistory.com


기본 화면 구성

01


필요 패키지 설치

아래 패키지는 필수 패키지 입니다.

drift: ^1.4.0 
sqlite3_flutter_libs: ^0.5.0  
path_provider: ^2.0.0  
path: ^1.8.0

 drift_dev: ^1.4.0  
build_runner: ^2.1.7

아래는 전체 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
  beamer: ^1.2.0
  drift: ^1.4.0
  sqlite3_flutter_libs: ^0.5.0
  path_provider: ^2.0.0
  path: ^1.8.0
  logger: ^1.1.0


dev_dependencies:
  flutter_test:
    sdk: flutter
  drift_dev: ^1.4.0
  build_runner: ^2.1.7

드리프트(drift) 사용을 위해 두가지 파일을 만듭니다. 

1. database.dart

 - 이 파일은 sqlite와 연결하고 CRUD를 구현하는 부분입니다. 

 - 전체 코드는 아래와 같고 공식 문서를 거의 그대로 붙여넣기하여 구현하였습니다. 

// These imports are only needed to open the database
import 'package:drift/native.dart';
import 'package:firebasetrain/drift/table.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
import 'package:drift/drift.dart';
import 'dart:io';

part 'database.g.dart'; // 공식 문서에 코드에서 유일하게 추가된 부분

LazyDatabase _openConnection() {
  // the LazyDatabase util lets us find the right location for the file async.
  return LazyDatabase(() async {
    // put the database file, called db.sqlite here, into the documents folder
    // for your app.
    final dbFolder = await getApplicationDocumentsDirectory();
    final file = File(p.join(dbFolder.path, 'db.sqlite'));
    return NativeDatabase(file);
  });
}

@DriftDatabase(tables: [Todos])
class MyDatabase extends _$MyDatabase {
  // we tell the database where to store the data with this constructor
  MyDatabase() : super(_openConnection());

  // you should bump this number whenever you change or add a table definition. Migrations
  // are covered later in this readme.

  Future<int> addTodos(TodosCompanion entry) {
    return into(todos).insert(entry);
  }

  // loads all todo entries
  Future<List<Todo>> get allTodoEntries => select(todos).get();

  Future delTodo(data) {
    return delete(todos).delete(data);
  }

  @override
  int get schemaVersion => 1;
}

2. table.dart

 - 이파일은 테이블을 만드는 부분 입니다. 

 - 아래는 id, title, content 를 구현한 부분입니다.

 -  아래 코드의 파일명이 table.dart 여서 part 'table.g.dart'; 입력했습니다.  

# 파일명이 table.dart 여서 part 'table.g.dart'; 입력했습니다. 

import 'package:drift/drift.dart';

# assuming that your file is called filename.dart. This will give an error at first,
# but it's needed for drift to know about the generated code

part 'table.g.dart';

# this will generate a table called "todos" for us. The rows of that table will
# be represented by a class called "Todo".


class Todos extends Table {
  IntColumn get id => integer().autoIncrement()();

  TextColumn get title => text().withLength(min: 6, max: 32)();

  TextColumn get content => text().named('body')();
}

 

3. flutter pub run build_runner build 로 코드 자동 생성

 - 여러가지 이 패키지를 사용하는데 필요한 코드를 자동으로 생성하는 부분입니다. 

 - flutter pub run build_runner build를 터미널에 입력하면 

    database.g.dart 파일과 table.g.dart 파일이 생성 될 것입니다. 

 

 

여기까지 했으면 기본적인 드리프트(drift) 사용 준비는 끝났습니다. 


길어 지는 것 같아 다음 포스팅으로 이어가겠습니다. 

2022.03.05 - [Flutter]drift로 todo list 만들기 예제 - 2탄(with drift, SQLite)

 

[Flutter]drift로 todo list 만들기 예제 - 2탄(with drift, SQLite)

Flutter로 todo list 만들기 1탄에 이어 2탄도 이어 가겠습니다. 1탄을 못보신 분은 아래 링크로 가시면 됩니다. https://jh-industry.tistory.com/52 [Flutter] todo list 만들기 예제 - 1탄(with drift, SQLite)..

jh-industry.tistory.com

 

댓글