株式会社ダイアログ Tech Blog

株式会社ダイアログのエンジニアチームが運営しています。

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

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

 インストール

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

dependencies:
  moor: ^3.3.1

dev_dependencies:
  moor_generator: ^3.3.1

テーブルを追加

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

  TextColumn get title => text()();

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

usemoorに追記

@UseMoor(tables: [
  Books,])

コマンドを実行

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

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

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

  @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の会社に勤務しております。 現在、エンジニアを募集していて、カジュアル面談も実施しているのでお気軽にご連絡ください!

https://www.wantedly.com/companies/company_3244501/projects