我想用 Flutter 建立一个 ObjectBox 数据库。我想用值预先填充数据库文件。安装应用程序时,数据库文件将被复制并由应用程序使用。我希望能够继续提供模式迁移。是否可以 ?
如何建立这种类型的架构?你有什么例子吗?
解决方案:通过@vaind 响应,我实现了一个数据库管理器,例如:
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import '../objectbox.g.dart';
/// Database manager manage database initialisation and configuration.
class DatabaseManager {
static DatabaseManager? _instance;
DatabaseManager._internal();
/// Singleton Factory constructor
factory DatabaseManager() {
if (_instance == null) {
_instance = DatabaseManager._internal();
}
return _instance!;
}
/// Initialize configuration of database:
/// - Init database file by copying.
/// - Open instance of database and close it.
Future<void> init() async {
await copyDatabaseFileFromAssets();
await testInstanceAndCloseIt();
}
/// Copy packaged database from assets folder to the app directory.
Future<void> copyDatabaseFileFromAssets() async {
// Get pre-populated db file.
ByteData data = await rootBundle.load("assets/databases/data.mdb");
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
// Search and create db file destination folder if not exist
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = documentsDirectory.path + "/objectbox/data.mdb";
if (!await File(path).exists()) {
var objectBoxDirectory = Directory(documentsDirectory.path + "/objectbox/");
if ((!await objectBoxDirectory.exists())) {
objectBoxDirectory.create();
}
// Copying source data into destination file.
await new File(path).writeAsBytes(bytes);
}
}
/// Open instance of database and close it.
Future<void> testInstanceAndCloseIt() async {
await openStore().then((Store store) {
store.close();
});
}
}