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 get database async { if (_database != null) return _database!; _database = await _initDatabase(); return _database!; } Future _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 addTask(ToDo todo) async { final db = await database; await db.insert( 'todos', todo.toJson(), conflictAlgorithm: ConflictAlgorithm.replace, ); } @override Future removeTask(int index) async { final db = await database; await db.delete( 'todos', where: 'id = ?', whereArgs: [index], ); } @override Future updateTask(int index, ToDo todo) async { final db = await database; await db.update( 'todos', todo.toJson(), where: 'id = ?', whereArgs: [index], ); } @override Future> fetchTasks() async { final db = await database; final maps = await db.query('todos'); return List.generate(maps.length, (i) { return ToDo.fromJson(maps[i]); }); } }