Important notice:Moor has been renamed to Drift. Learn more here.

Existing databases

Using drift with an existing database

You can use drift with a pre-propulated database that you ship with your app.

Including the database

First, create the sqlite3 database you want to ship with your app. You can create a database with the sqlite3 CLI tool on your development machine. Of course, you can also create the database programmatically by using a library like sqlite3 (or even drift itself).

To ship that database to users, you can include it as a flutter asset. Simply include it in your pubspec:

    - assets/my_database.db

Extracting the database

To initialize the database before using drift, you need to extract the asset from your app onto the device. In drift, you can use a LazyDatabase to perform that work just before your drift database is opened:

import 'package:drift/drift.dart';
import 'package:flutter/services.dart' show rootBundle;

LazyDatabase _openConnection() {
  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, 'app.db'));
    if (!await file.exists()) {
        // Extract the pre-populated database file from assets
        final blob = await rootBundle.load('assets/my_database.db');
        final buffer = blob.buffer;
        await file.writeAsBytes(buffer.asUint8List(blob.offsetInBytes, blob.lengthInBytes));

    return NativeDatabase(file);

Finally, use that method to open your database:

@DriftDatabase(tables: [Todos, Categories])
class MyDatabase extends _$MyDatabase {
  MyDatabase() : super(_openConnection());

  // ...