CPD_2024_todo/lib/storage/sqlite_todo_storage.dart

68 lines
1.6 KiB
Dart

import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import '../models/todo.dart';
import 'todo_storage.dart';
class SQLiteToDoStorage implements ToDoStorage {
Database? _database;
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<Database> _initDatabase() async {
final path = join(await getDatabasesPath(), 'todo_database.db');
return openDatabase(
path,
onCreate: (db, version) {
return db.execute(
'CREATE TABLE todos(id INTEGER PRIMARY KEY, title TEXT, description TEXT, deadline TEXT, priority TEXT, isCompleted INTEGER)',
);
},
version: 1,
);
}
@override
Future<void> addTask(ToDo todo) async {
final db = await database;
await db.insert(
'todos',
todo.toJson(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
@override
Future<void> removeTask(int index) async {
final db = await database;
await db.delete(
'todos',
where: 'id = ?',
whereArgs: [index],
);
}
@override
Future<void> updateTask(int index, ToDo todo) async {
final db = await database;
await db.update(
'todos',
todo.toJson(),
where: 'id = ?',
whereArgs: [index],
);
}
@override
Future<List<ToDo>> fetchTasks() async {
final db = await database;
final maps = await db.query('todos');
return List.generate(maps.length, (i) {
return ToDo.fromJson(maps[i]);
});
}
}