From c9deb726e094592b5deaa73a2cf215be48051c76 Mon Sep 17 00:00:00 2001 From: SomnusVeritas Date: Wed, 8 Nov 2023 12:57:45 +0100 Subject: [PATCH] implemented undo button and proper sorting --- lib/models/todo.dart | 9 +++------ lib/pages/todo_create_page.dart | 7 ++++++- lib/services/dbhelper.dart | 2 +- lib/widgets/todo_list.dart | 20 +++++++++++++++++++- 4 files changed, 29 insertions(+), 9 deletions(-) diff --git a/lib/models/todo.dart b/lib/models/todo.dart index 7ea97cc..9b70402 100644 --- a/lib/models/todo.dart +++ b/lib/models/todo.dart @@ -1,7 +1,5 @@ import 'package:isar/isar.dart'; -import '../services/dbhelper.dart'; - part 'todo.g.dart'; @collection @@ -13,11 +11,10 @@ class Todo { bool done; Todo({ - int? index, + required this.id, required this.title, + required this.createdAt, this.description = '', - DateTime? createdTime, this.done = false, - }) : createdAt = createdTime ?? DateTime.now(), - id = index ?? DbHelper.nextTodoId; + }); } diff --git a/lib/pages/todo_create_page.dart b/lib/pages/todo_create_page.dart index 9518647..0d35ca9 100644 --- a/lib/pages/todo_create_page.dart +++ b/lib/pages/todo_create_page.dart @@ -56,7 +56,12 @@ class _CreateTodoPageState extends State { } void _onSubmitted() { - DbHelper.addOrUpdateTodo(Todo(title: _title, description: _description)); + DbHelper.addOrUpdateTodo(Todo( + id: DbHelper.nextTodoId, + title: _title, + description: _description, + createdAt: DateTime.now(), + )); Navigator.of(context).pop(); } } diff --git a/lib/services/dbhelper.dart b/lib/services/dbhelper.dart index 22846c7..3efb614 100644 --- a/lib/services/dbhelper.dart +++ b/lib/services/dbhelper.dart @@ -17,7 +17,7 @@ class DbHelper { } static List fetchTodos() => - _isar.todos.where().doneEqualTo(false).findAll(); + _isar.todos.where().doneEqualTo(false).sortByCreatedAtDesc().findAll(); static void addOrUpdateTodo(Todo todo) => _isar.write((isar) => isar.todos.put(todo)); diff --git a/lib/widgets/todo_list.dart b/lib/widgets/todo_list.dart index 9915bb5..75a0027 100644 --- a/lib/widgets/todo_list.dart +++ b/lib/widgets/todo_list.dart @@ -39,7 +39,11 @@ class _TodoListState extends State { tileColor: Theme.of(context).colorScheme.primaryContainer, title: Text(todo.title), trailing: IconButton( - onPressed: () {}, + onPressed: () { + todo.done = true; + DbHelper.addOrUpdateTodo(todo); + _showSnackbar(todo); + }, icon: Icon( Icons.check_box, color: Theme.of(context).colorScheme.primary, @@ -47,4 +51,18 @@ class _TodoListState extends State { ), ); } + + void _showSnackbar(Todo todo) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text('Todo done'), + action: SnackBarAction( + label: 'Undo', + onPressed: () { + todo.done = false; + DbHelper.addOrUpdateTodo(todo); + }), + ), + ); + } }