问题描述
我想在我的应用程序中使用sqflite。为此,我尝试遵循本教程:https://flutter.dev/docs/cookbook/persistence/sqlite。但是,我不知道将代码放置在应用程序中的何处。在本教程中,代码似乎放置在main()函数中-但是,如果这样做,如何在其他文件中调用insert,update和delete方法?
更新:
根据@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',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',whereArgs: [id],);
}
}
}
解决方法
否,无论您在何处创建数据库都没关系。
您可以创建一个文件databaseServices.dart
来管理数据库服务。然后,您可以轻松管理代码。
在食谱中,它们只是显示一个示例,说明如何使用sqlflite
。
但是,如果您要在WidgetsFlutterBinding.ensureInitialized();
方法中执行异步任务,则应该在main()
方法中将此行main()
放在任何内容之前。
更新:
要在其他文件中执行CRUD,
- 将您要执行CRUD的
databaseServices.dart
文件导入该文件。
import 'databaseServices.dart';
DataBaseServices db=DataBaseServices();// create an object (DataBaseServices is the name of the class)
//Now,you can access all the methods,db.delete()//example
或者,如果您不想在databaseServices.dart
文件中创建类,并且希望将每个函数都保留为顶级函数,则可以执行以下操作。
import 'databaseServices.dart' as db;
//Now,you can access all the top level functions or variables.
db.delete()//example.
更新2:-
要使数据库可以使用所有功能,
- 将Future数据库移至any()方法之外,并将其放置在类名的正下方。 (将其设置为全局,以便每个函数都可以访问它),请注意,我删除了“ final”关键字,因为稍后我们将使用任何方法对其进行初始化。现在,以任何方法执行您的操作,而不是最终的Future database = / yoir代码,而是执行database = //您的代码..通过此操作,您将初始化数据库变量,并作为数据库变量是全局变量(在任何函数外部,类内部声明),任何函数都可以访问它。但是必须记住,在调用需要数据库的任何其他方法之前必须先初始化数据库,因为如果您不在任何其他函数之前调用what()方法,那么该数据库将不会被初始化,因此您的其他功能将无法正常工作。
示例
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'counter.dart';
class DatabaseServices {
Future<Database> database;//making database global so that every function inside the class can access it.
void whatever() async {
// Open the database and store the reference.
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,);
}//Function whatever () ends here
// 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',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',whereArgs: [id],);
}
}
现在,由于没有嵌套函数,因此您可以轻松创建类的对象,并根据需要轻松调用函数:)