cpd_2024_todo/lib/database/SharedPref.dart

84 lines
2.5 KiB
Dart
Raw Permalink Normal View History

2024-10-30 23:41:56 +01:00
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<SharedPreferences> get _prefs async {
SharedPreferences preferences = await SharedPreferences.getInstance();
if (preferences.getString(todoKey) == null) {
preferences.setString(todoKey, "[]");
}
return preferences;
}
@override
Future<ToDoItem> insertToDoItem(ToDoItem todo) async {
SharedPreferences preferences = await _prefs;
final String prefContent = preferences.getString(todoKey)!;
final List<dynamic> fileJson = jsonDecode(prefContent);
List<ToDoItem> 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<void> deleteToDoItem(int id) async {
SharedPreferences preferences = await _prefs;
final String prefContent = preferences.getString(todoKey)!;
final List<dynamic> fileJson = jsonDecode(prefContent);
List<ToDoItem> todoList =
fileJson.map((todo) => ToDoItem.fromJson(todo)).toList();
todoList.removeWhere((todo) => todo.id == id);
preferences.setString(todoKey, jsonEncode(todoList));
}
@override
Future<List<ToDoItem>> getToDoItems() async {
SharedPreferences preferences = await _prefs;
final String prefContent = preferences.getString(todoKey)!;
final List<dynamic> fileJson = jsonDecode(prefContent);
return fileJson.map((todo) => ToDoItem.fromJson(todo)).toList();
}
@override
Future<void> updateToDoItem(ToDoItem todo) async {
SharedPreferences preferences = await _prefs;
final String prefContent = preferences.getString(todoKey)!;
final List<dynamic> fileJson = jsonDecode(prefContent);
List<ToDoItem> 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));
}
}