Flutter Drift package | Can you define queries in a separate file?

167 Views Asked by At

...or better yet, define them in various places like each entity's Model or Repository.

My goal is to keep my database.dart file from becoming miles long because of ~6 CRUD functions per domain model, plus this also just fits the modular approach more IMO. I may just be missing an obvious pattern or something. Somewhat new to Flutter so please point me in the right direction.

Ta

I already have my Tables registered in separate files, so looking for something similar for Queries.

1

There are 1 best solutions below

0
akash murugesh On

This can be achieved using DAOs in drift, view here.

More details regarding the solution:

  1. Create a file for the queries. For example queries.dart:
// file name: queries.dart
part 'queries.g.dart';

@DriftAccessor(tables: [Users]) // the tables used
class UsersDao extends DatabaseAccessor<AppDatabase> with _$UsersDaoMixin {

  UsersDao(super.db);

  // all your queries will go here
  Future<List<User>> getUsers() async { // sample query FYR
    return await select(users).get();
  }
}

Note: Make sure that the file name and the name provided in part matches. In this case queries.dart matches with part 'queries.g.dart'.

  1. Make sure to change the annotation in the database file. For example database.dart:
// file name: database.dart
part 'database.g.dart';

@DriftDatabase(
  tables: [
    Users,
  ],
  daos: [
    UsersDao,
  ], // add this
)
class AppDatabase extends _$AppDatabase {
   // fill your code here, left blank intentionally
}
  1. Re-run the code generation using the either of the commands:
  • dart run build_runner build : generates all the required code once.
  • dart run build_runner watch : watches for changes in your sources and generates code with incremental rebuilds. This is suitable for development sessions.

Bonus: You can also write SQL queries along with table schemas in .drift files and map them to methods and call it like the same, view here