How to insert data on first app run? #1404
-
I followed official getting started guide and made a simple clean setup. Can someone explain step by step how to insert initial data on first run of an app? I did some search, but did not find a clear answer. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can insert data when your database gets created, which should come pretty close. You can use the MigrationStrategy(
onCreate: (m) async {
await m.createAll(); // create all tables
await into(myTable).insert(...); // insert on first run.
}
) You can call all methods from your database in the migration callback (including things like batches or transactions), so you can just insert data in the create callback. Another approach would be to create a sqlite3 file containing the initial rows as an asset and then using that instead of creating a new sqlite3 database inside your app. Something like // use this instead of the direct `VmDatabase`
QueryExecutor _openDb() {
return LazyDatabase(() async {
File file = ...;
if (!await file.exists()) {
// create database file from asset
}
return VmDatabase(file);
});
} |
Beta Was this translation helpful? Give feedback.
You can insert data when your database gets created, which should come pretty close. You can use the
onCreate
callback in your migration behavior to run inserts after creating all tables:You can call all methods from your database in the migration callback (including things like batches or transactions), so you can just insert data in the create callback.
Another approach would be to create a sqlite3 file containing the initial rows as an asset and then using that instead of creating a new sqlite3 database inside your app. Something like