Files
flisp_app/lib/service/todo_service.dart

69 lines
1.8 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:flisp_app/models/todo.dart';
import 'package:hive_flutter/hive_flutter.dart';
class TodoService {
static const String boxName = 'todos';
Box<Todo> get box => Hive.box<Todo>(boxName);
Future<bool> addTodo(Todo todo) async {
try {
await box.add(todo);
return true;
} catch (e) {
return false;
}
}
List<Todo> getAllTodos(TodoSortMode mode) {
if (mode == TodoSortMode.time) {
return box.values.toList()
..sort((a, b) {
// 先按是否有 dueDate 分组:有时间的排前面
if (a.dueDate != null && b.dueDate == null) {
return -1; // a有时间b没有时间a排在前面
} else if (a.dueDate == null && b.dueDate != null) {
return 1; // a没有时间b有时间b排在前面
}
// 都有 dueDate按 dueDate 排序
else if (a.dueDate != null && b.dueDate != null) {
return a.dueDate!.compareTo(b.dueDate!); // 最近的在前面
}
// 都没有 dueDate按 updateTime 排序
else {
return b.updateTime.compareTo(a.updateTime); // 最近的在前面
}
});
} else {
return box.values.toList()
..sort((a, b) => b.priorityIndex.compareTo(a.priorityIndex));
}
}
List<Todo> getAllTodosByYear(int year) {
return box.values
.toList()
.where((todo) => todo.createTime.year == year)
.toList();
}
Future<bool> updateTodo(Todo todo) async {
try {
todo.updateTime = DateTime.now();
await todo.save();
return true;
} catch (e) {
return false;
}
}
Future<bool> deleteTodo(Todo todo) async {
try {
await todo.delete();
return true;
} catch (e) {
return false;
}
}
}