【发布时间】:2020-08-30 05:37:38
【问题描述】:
我想在我的应用程序中使用 sqflite。为此,我正在尝试遵循本教程:https://flutter.dev/docs/cookbook/persistence/sqlite。但是,我不知道在我的应用程序中放置代码的位置。在本教程中,代码似乎放在 main() 函数中 - 但是,如果这样做,我如何在其他文件中调用插入、更新和删除方法?
更新:
按照@Madhavam Shahi 的建议,我创建了一个文件databaseServices.dart。现在,在另一个文件中,我正在导入 databaseServices.dart 并尝试如下使用它:
import 'databaseServices.dart';
DataBaseServices db=DataBaseServices();
db.delete() //example
但是,它不起作用。我认为databaseServices.dart 的结构不正确,但我无法发现错误。我知道我一定犯了一个非常新手的错误。这是databaseServices.dart的代码:
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'counter.dart';
class DatabaseServices {
void whatever() async {
// Open the database and store the reference.
final Future<Database> database = openDatabase(
// Set the path to the database.
join(await getDatabasesPath(), 'counter_database.db'),
// When the database is first created, create a table to store counters;
onCreate: (db, version) {
// Run the CREATE TABLE statement on the database.
return db.execute(
"CREATE TABLE counters(id INTEGER PRIMARY KEY, name TEXT, value INTEGER)",
);
},
// Set the version. This executes the onCreate function and provides a
// path to perform database upgrades and downgrades.
version: 1,
);
// Define a function that inserts counters into the database.
Future<void> insertCounter(Counter counter) async {
// Get a reference to the database.
final Database db = await database;
// Insert the Counter into the correct table. Here, if a counter is inserted twice,
// it replace any previous data.
await db.insert(
'counters',
counter.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
// A method that retrieves all the counters from the counters table.
Future<List<Counter>> counters() async {
// Get a reference to the database.
final Database db = await database;
// Query the table for all the Counters.
final List<Map<String, dynamic>> maps = await db.query('counters');
// Counvert the List<Map<String, dynamic>> into a List<Counter>
return List.generate(maps.length, (i) {
return Counter(
id: maps[i]['id'],
name: maps[i]['name'],
value: maps[i]['value'],
);
});
}
// Method to update a Counter in the database
Future<void> updateCounter(Counter counter) async {
final db = await database;
await db.update(
'counters',
counter.toMap(),
where: "id = ?",
whereArgs: [counter.id],
);
}
//Delete a Counter from the database
Future<void> deleteCounter(int id) async {
final db = await database;
await db.delete(
'counters',
where: "id = ?",
whereArgs: [id],
);
}
}
}
【问题讨论】:
标签: sqlite flutter dart sqflite