cpd_2024_todo/lib/buisness/ToDoProvider.dart

60 lines
1.6 KiB
Dart

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'ToDoItem.dart';
class ToDoProvider with ChangeNotifier {
List<ToDoItem> _toDoList = [];
List<ToDoItem> get toDoList => _toDoList;
ToDoProvider() {
_loadFromPrefs();
}
void addToDo(ToDoItem item) {
_toDoList.add(item);
_saveToPrefs();
notifyListeners();
}
void updateStatus(int index, String status) {
_toDoList[index].status = status;
_saveToPrefs();
notifyListeners();
}
// Save To-Do list to shared preferences as JSON
Future<void> _saveToPrefs() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<Map<String, dynamic>> jsonData = _toDoList.map((item) => item.toJson()).toList();
await prefs.setString('toDoList', json.encode(jsonData));
}
// Load To-Do list from shared preferences as JSON
Future<void> _loadFromPrefs() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? toDoData = prefs.getString('toDoList');
if (toDoData != null) {
List<dynamic> jsonData = json.decode(toDoData);
_toDoList = jsonData.map((item) => ToDoItem.fromJson(item)).toList();
}
notifyListeners();
}
void sortByName() {
_toDoList.sort((a, b) => a.name.compareTo(b.name));
notifyListeners();
}
void sortByDueDate() {
_toDoList.sort((a, b) => a.dueDate.compareTo(b.dueDate));
notifyListeners();
}
void sortByStatus() {
_toDoList.sort((a, b) => a.status.compareTo(b.status));
notifyListeners();
}
}