如何使用桌面上的 Sqflite 包将数据库文件名更改为自定义路径,例如 Flutter 中的项目文件夹?
当以下代码在名为 DatabaseHelper 的类中运行时:
Future<Database> _initDatabase() async {
// Initialize sqflite as sqflite_common_ffi if you are on desktop
dev.log(" In DatabaseHelper:\n _initDatabase(): open database.");
if (Platform.isWindows || Platform.isLinux) {
dev.log(" On desktop.");
sqfliteFfiInit();
}else{
dev.log(" On mobile.");
}
databaseFactory = databaseFactoryFfi;
final databasePath = await databaseFactory.getDatabasesPath();
print("Databese path: ======> $databasePath");
final path = p.join(databasePath, SqlExp.fileName);
return await databaseFactory.openDatabase(
path,
options: OpenDatabaseOptions(
version: SqlExp.version,
onCreate: _onCreate,
),
);
}
输出为:
[log] In DatabaseHelper:
[log] _initDatabase(): open database.
[log] On desktop.
flutter: Databese path: ======> /home/(pc-hostname)/Flutter/projects/(projectName)/.dart_tool/sqflite_common_ffi/databases
但是请求的结果是一样的:
/home/(pc-hostname)/Flutter/projects/(projectName)/.databases/customPath
getDatabasesPath()
不允许你这样做。 Flutter 或 Dart 中是否有更好的函数(如果可能的话,无需外部包)可以让您获取当前工作目录,如果有这样的函数,从长远来看是否可以或更优化地使用而不是使用getDatabasesPath()
Sqflite 包附带的功能应该可以很好地收集,还是我弄错了?
我尝试使用path_provider包中的
getApplicationDocumentsDirectory()
,但是,我期望在我的项目文件夹中有一个自定义路径目录,我不希望用户轻松访问数据库。
您可以使用 Dart 的 Directory 类来获取当前工作目录。
class DatabaseHelper {
static final DatabaseHelper instance = DatabaseHelper._init();
static Database? _database;
DatabaseHelper._init();
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<Database> _initDatabase() async {
dev.log(" In DatabaseHelper:\n _initDatabase(): open database.");
if (Platform.isWindows || Platform.isLinux) {
dev.log(" On desktop.");
sqfliteFfiInit();
} else {
dev.log(" On mobile.");
}
databaseFactory = databaseFactoryFfi;
// Get the current working directory
final currentDir = Directory.current.path;
dev.log("Current working directory: $currentDir");
// Define your custom path
final customPath = p.join(currentDir, '.databases', 'customPath');
dev.log("Custom database path: $customPath");
// Ensure the directory exists
final customDir = Directory(customPath);
if (!await customDir.exists()) {
await customDir.create(recursive: true);
}
final path = p.join(customPath, SqlExp.fileName);
return await databaseFactory.openDatabase(
path,
options: OpenDatabaseOptions(
version: SqlExp.version,
onCreate: _onCreate,
),
);
}
Future _onCreate(Database db, int version) async {
// Your database creation logic here
}
}