Reference a Table which is in another package?
I am currently working on a modular Flutter framework, and I would like to ask for your advice regarding Drift integration in this setup.
My architecture is based on separate packages:
flamework_base: contains a base database class extending _$DatabaseDrift.
flamework_customer: defines a CustomerModel extends Table and a specific database class extending the base one.
main project: imports both flamework_base and flamework_customer, and should generate the full database schema with build_runner.
Here is a simplified version of the code:
In flamework_base:
@DriftDatabase(tables: [])
class DatabaseDriftBase extends _$DatabaseDrift {
DatabaseDriftBase(super.e);
@override
int get schemaVersion => 1;
}
In flamework_customer:
class CustomerModel extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text()();
}
In the main project:
@DriftDatabase(tables: [CustomerModel])
class DatabaseDrift extends DatabaseDriftBase {
DatabaseDrift(super.e);
@override
int get schemaVersion => 2;
}
The problem I am facing is that when I run
flutter pub run build_runner build from the main project, I get the following warning:
The referenced element, CustomerModel, is not understood by drift.
This is an artifact of how drift interacts with build_runner. The short answer is that I think framework_customer needs to depend on drift_dev. The reason this is a requirement is that drift generates intermediate (hidden) JSON files with partial analysis results during the build to speed it up. So when drift wants to analyze a file and can't find that hidden JSON, it assumes there's no relevant table defined in that file. But when you run drift across multiple packages, the JSONs only get generated when build_runner applies drift_dev on the relevant package.
More generally though, I think for cases like this you'll want to look at modular code generation on all packages. That avoids this issue and also ensures drift generates less duplicate code (at the moment the full database code would be generated for both database classes, so most tables get generated twice).