cpd_2024_todo/lib/database/Sqlite.dart

89 lines
2.0 KiB
Dart
Raw Permalink Normal View History

2024-10-29 13:13:10 +01:00
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:todo/database/DatabaseInterface.dart';
import '../buisness/ToDoItem.dart';
class Sqlite implements DatabaseInterface {
static final Sqlite _instance = Sqlite._internal();
factory Sqlite() => _instance;
static Database? _database;
Sqlite._internal();
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<Database> _initDatabase() async {
String path = join(await getDatabasesPath(), 'todo_database.db');
print(path);
return await openDatabase(
path,
version: 1,
onCreate: (db, version) async {
await db.execute(
'''
CREATE TABLE todo_items(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
description TEXT,
dueDate TEXT,
status TEXT
)
''',
);
},
);
}
// ToDoItem hinzufügen
2024-10-29 19:06:41 +01:00
@override
2024-10-29 13:13:10 +01:00
Future<void> insertToDoItem(ToDoItem item) async {
final db = await database;
final id = await db.insert(
'todo_items',
2024-10-30 23:41:56 +01:00
item.toJson(),
2024-10-29 13:13:10 +01:00
conflictAlgorithm: ConflictAlgorithm.replace,
);
item.id = id;
}
2024-10-29 19:06:41 +01:00
@override
2024-10-29 13:13:10 +01:00
Future<List<ToDoItem>> getToDoItems() async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.query('todo_items');
return List.generate(maps.length, (i) {
2024-10-30 23:41:56 +01:00
return ToDoItem.fromJson(maps[i]);
2024-10-29 13:13:10 +01:00
});
}
2024-10-29 19:06:41 +01:00
@override
2024-10-29 13:13:10 +01:00
Future<void> deleteToDoItem(int id) async {
final db = await database;
await db.delete(
'todo_items',
where: 'id = ?',
whereArgs: [id],
);
}
2024-10-29 19:06:41 +01:00
@override
2024-10-29 13:13:10 +01:00
Future<void> updateToDoItem(ToDoItem item) async {
final db = await database;
await db.update(
'todo_items',
2024-10-30 23:41:56 +01:00
item.toJson(),
2024-10-29 13:13:10 +01:00
where: 'id = ?',
whereArgs: [item.id],
);
}
Future<void> closeDatabase() async {
final db = await database;
await db.close();
}
}