import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:todo/database/DatabaseInterface.dart'; import '../buisness/ToDoItem.dart'; class SharedPref implements DatabaseInterface { final todoKey = "todos"; Future get _prefs async { SharedPreferences preferences = await SharedPreferences.getInstance(); if (preferences.getString(todoKey) == null) { preferences.setString(todoKey, "[]"); } return preferences; } @override Future insertToDoItem(ToDoItem todo) async { SharedPreferences preferences = await _prefs; final String prefContent = preferences.getString(todoKey)!; final List fileJson = jsonDecode(prefContent); List todoList = fileJson.map((todo) => ToDoItem.fromJson(todo)).toList(); todo.id = DateTime.now().millisecondsSinceEpoch; todoList.add(todo); preferences.setString(todoKey, jsonEncode(todoList)); return todo; } @override Future deleteToDoItem(int id) async { SharedPreferences preferences = await _prefs; final String prefContent = preferences.getString(todoKey)!; final List fileJson = jsonDecode(prefContent); List todoList = fileJson.map((todo) => ToDoItem.fromJson(todo)).toList(); todoList.removeWhere((todo) => todo.id == id); preferences.setString(todoKey, jsonEncode(todoList)); } @override Future> getToDoItems() async { SharedPreferences preferences = await _prefs; final String prefContent = preferences.getString(todoKey)!; final List fileJson = jsonDecode(prefContent); return fileJson.map((todo) => ToDoItem.fromJson(todo)).toList(); } @override Future updateToDoItem(ToDoItem todo) async { SharedPreferences preferences = await _prefs; final String prefContent = preferences.getString(todoKey)!; final List fileJson = jsonDecode(prefContent); List todoList = fileJson.map((todo) => ToDoItem.fromJson(todo)).toList(); final todoToUpdate = todoList.firstWhere((t) => t.id == todo.id); final todoToUpdateIndex = todoList.indexOf(todoToUpdate); todoToUpdate.name = todo.name; todoToUpdate.description = todo.description; todoToUpdate.status = todo.status; todoToUpdate.dueDate = todo.dueDate; todoList.replaceRange(todoToUpdateIndex, todoToUpdateIndex, [todoToUpdate]); preferences.setString(todoKey, jsonEncode(todoList)); } }