我想从sqlite数据库表中选择索引,然后将值传递/分配给变量。我有一个model.dart
文件,其中包含index
的声明,从DatabaseHelper.dart
文件中的数据库中获取并将其传递到Selection.dart
文件中。
Model.dart
class Selected {
int id;
int index;
Selected();
}
我已经设置好databaseHelper.dart
DatabaseHelper.dart
这是我要从中调用其值的文件。
class DatabaseHelper {
static DatabaseHelper _databaseHelper; // Singleton databaseHelper
static Database _database; // Singleton database
// Named constructor to create instance of the DatabaseHelper
DatabaseHelper._createInstance();
factory DatabaseHelper() {
if (_databaseHelper == null) {
_databaseHelper = DatabaseHelper
._createInstance(); // this is executed only once , singleton object
}
return _databaseHelper;
}
// Declarations
String selectedTable = 'selected__table';
String colID = 'id';
String colIndex = 'index';
// Getting the database
Future<Database> get database async {
if (_database == null) {
// Checking if the database is empty
_database =
await initializeDatabase(); // if database is empty call the database initialization function initializeDatabase()
}
return _database;
}
// Function for initializing the database if the database is empty and providing the directory for the database
Future<Database> initializeDatabase() async {
// Get the directory path for both android and ios to store database
Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, 'selected.db'); // database directory declaration
var selectedDatabase =
await openDatabase(path, version: 1, onCreate: _createDB);
return selectedDatabase;
}
// Creating database table
void _createDB(Database db, int newVersion) async {
await db.execute('CREATE TABLE $selectedTable($colID INTEGER PRIMARY KEY AUTOINCREMENT, $colIndex INTEGER)');
insertSelected(db);
}
// Fetch operation in the database
Future getSelected() async {
Database db = await this.database;
int id = 1;
var selectedIndex = db.rawQuery('SELECT index FROM $selectedTable WHERE id = $id');
return selectedIndex;
}
}
Selection.dart
在这个文件中,我想从databaseHelper.dart文件返回selectedIndex
并将其分配给selectedLanguageIndex