我需要在flutter应用程序中创建一个动态命名数据库的连接,我如何将参数传递给一个具有数据库名称的类,并返回一个连接?
我知道getter不能接受参数,我尝试添加setter函数来设置_databaseName,但没有成功。
我有一个数据库类如下:
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart' show join;
import 'dart:io' as io;
import 'package:path_provider/path_provider.dart';
class DatabaseHelper {
static const _databaseName = "tinkershell.db";
static const _databaseVersion = 1;
DatabaseHelper._privateConstructor(); // make this a singleton class
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database? _database; // only have a single app-wide reference to the database
static String path = "";
Future<Database> get database async => _database ??= await _initDatabase();
_onOpen(Database db) async {
//do something here later
}
Future<Database> _initDatabase() async {
io.Directory documentDirectory = await getApplicationDocumentsDirectory();
path = join(documentDirectory.path , _databaseName);
return await openDatabase(
join(path),
version: _databaseVersion,
onOpen: _onOpen,
);
}
}
我成功地调用了它,使用的函数如下:
Future<void> createNewApplication() async {
Database db = await DatabaseHelper.instance.database;
final data = db.rawQuery(" SELECT * from myTable");
}
我想打这样的电话
Future<void> createNewApplication() async {
Database db = await DatabaseHelper.instance.database("database1234");
final data = db.rawQuery(" SELECT * from myTable");
}
2条答案
按热度按时间llmtgqce1#
这是否可行:
q8l4jmvw2#
然后使用
method
而不是getter
并传递数据库名称,如下所示: