gpt4 book ai didi

sqlite - 从单独的文件在main.dart中使用SQLite?

转载 作者:行者123 更新时间:2023-12-03 03:38:38 24 4
gpt4 key购买 nike

我遵循了flutter文档中的这个简单示例。但是,这是写在单独的文件(db_test.db)中的。我的目标是将数据转换为ListView。那么,我将如何使用CRUD操作(例如在main.dart中检索数据)?我可以将其添加到我的main.dart文件中,但我想保持其清洁和分离。

Official Flutter tutorial

我的db.dart文件

void main () async {
final database = openDatabase(

join(await getDatabasesPath(), 'to_do.db'),
onCreate: (db, version) {
return db.execute("CREATE TABLE tasks(id INTEGER PRIMARY KEY, title TEXT, created TEXT, INTEGER is_complete)");
},
version: 1,
);

Future<void> insertTask (Task task) async {
final Database db = await database;

await db.insert(
'tasks',
task.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace
);
}

Future<List<Task>> tasks () async {
final Database db = await database;

final List<Map<String, dynamic>> maps = await db.query('tasks');

return List.generate(maps.length, (i) {
return Task(
id: maps[i]['id'],
title: maps[i]['title'],
created: maps[i]['created'],
isComplete: maps[i]['is_complete']
);
});
}

Future<void> updateTask(Task task) async {
// Get a reference to the database.
final db = await database;

// Update the given Dog.
await db.update(
'tasks',
task.toMap(),
// Ensure that the Dog has a matching id.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [task.id],
);
}

Future<void> deleteTask(int id) async {
// Get a reference to the database.
final db = await database;

// Remove the Dog from the database.
await db.delete(
'tasks',
// Use a `where` clause to delete a specific dog.
where: "id = ?",
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [id],
);
}
}

最佳答案

您可以使用静态成员创建一个包含Class的新文件来提供帮助。静态成员可确保在整个应用程序中仅创建一个数据库实例。

class DatabaseHelper {
static Database _database;

///Returns db instance if already opened
///else call the initDatabase
static Future<Database> getDBConnector() async {
if (_database != null) {
return _database;
}

return await _initDatabase();
}

///Open DB Connection, returns a Database instance.
///
static Future<Database> _initDatabase() async {
_database = await openDatabase(
join(await getDatabasesPath(), "my_path.db"),

onCreate: (db, version) async {
//on create
},
version: 1,
);

return _database;
}

//put your CRUD in static function
static Future<void> insertTask (Task task) async {
final Database db = await getDBConnector();

await db.insert(
'tasks',
task.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace
);
}

//the same with edit, delete
}

然后在另一个文件(如main.dart)中,您可以这样调用它:

import "./databaseHelper.dart";
void caller() async{
//create task

//insert
await DatabaseHelper.insertTask(task);
}

确保调用方是异步的。

关于sqlite - 从单独的文件在main.dart中使用SQLite?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58943633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com