LoginSignup
1
1

More than 1 year has passed since last update.

[Flutter]moorを使用したテーブルの作り方

Last updated at Posted at 2021-12-16

Flutterにおいて、moorを使用したDBの作成方法を簡単に記載します。
手順にフォーカスするので、細かい解説などは省いてます。

 インストール

pubspec.yamlに追加します(バージョンは確認してください)

pubspec.yaml
dependencies:
  moor: ^3.3.1

dev_dependencies:
  moor_generator: ^3.3.1

テーブルを追加

db.dart
@DataClassName('Book')
class Books extends Table {
  IntColumn get id => integer().autoIncrement()(); //idの自動採番

  TextColumn get title => text()();

  TextColumn get content => text().nullable()(); //nullの許可
}

usemoorに追記

db.dart
@UseMoor(tables: [
  Books,])

コマンドを実行

下記コマンドをターミナルで実行し、アプリを再起動します。

terminal
flutter packages pub run build_runner build --delete-conflicting-outputs

マイグレーションの追加(追加で作成する場合)

db.dart
  @override
  int get schemaVersion => 2;

  @override
  MigrationStrategy get migration => MigrationStrategy(onCreate: (Migrator m) {
        return m.createAll();
      }, onUpgrade: (Migrator m, int from, int to) async {
        if (from < 2) {
          // we added the dueDate property in the change from version 2
          await m.createTable(books);
      }
  });

最後に

私は現在、株式会社ダイアログという物流×ITの会社に勤務しております。
現在、エンジニアを募集していて、カジュアル面談も実施しているのでお気軽にご連絡ください!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1