Add existing databases not work #1203
-
import 'package:flutter/services.dart' show rootBundle;
import 'package:moor/ffi.dart';
import 'package:moor/moor.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
LazyDatabase _openConnection() {
return LazyDatabase(() async {
/// put the database file, called db_orion here, into the documents folder for your app.
final dbFolder = await getApplicationDocumentsDirectory();
final file = File(path.join(dbFolder.path, 'db_orion'));
if (!await file.exists()) {
/// Extract the pre-populated database file from assets
final blob = await rootBundle.load('assets/database/db_orion');
final buffer = blob.buffer;
await file.writeAsBytes(
buffer.asUint8List(blob.offsetInBytes, blob.lengthInBytes));
}
return VmDatabase(file, logStatements: true);
});
}
@UseMoor(tables: [
....
])
class AppDatabase extends _$AppDatabase {
AppDatabase() : super(_openConnection());
@override
int get schemaVersion => 1;
} Library: Assets: flutter:
uses-material-design: true
assets:
- assets/database/db_orion When I run for the first time, I don't see on the log that the DB or event table is created. And when I check on my device, the DB is not created. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
It looks Ok at first glance. This is what I do at the start of the app, but you can also let it open itself automatically when running any SQL (SELECT, UPDATE, INSERT...) final AppDatabase appDb = AppDatabase();
await appDb.executor.ensureOpen(appDb); |
Beta Was this translation helpful? Give feedback.
-
I fix with this code (this code didn't available on the moor docs or different within the moor docs) /// This function for load db from the assets
LazyDatabase _openConnection() {
return LazyDatabase(() async {
/// put the database file, called db_orion.db here, into the documents folder for your app.
final dbFolder = await getDatabasesPath();
final file = File(join(dbFolder, 'db_orion'));
if (!await file.exists()) {
/// Extract the pre-populated database file from assets
final blob = await rootBundle.load('assets/database/db_orion');
await file.writeAsBytes(blob.buffer.asUint8List());
}
return FlutterQueryExecutor.inDatabaseFolder(
path: file.path,
logStatements: true,
);
});
} |
Beta Was this translation helpful? Give feedback.
I fix with this code (this code didn't available on the moor docs or different within the moor docs)