implemented undo button and proper sorting

This commit is contained in:
SomnusVeritas
2023-11-08 12:57:45 +01:00
parent 91ce231b04
commit c9deb726e0
4 changed files with 29 additions and 9 deletions

View File

@@ -1,7 +1,5 @@
import 'package:isar/isar.dart'; import 'package:isar/isar.dart';
import '../services/dbhelper.dart';
part 'todo.g.dart'; part 'todo.g.dart';
@collection @collection
@@ -13,11 +11,10 @@ class Todo {
bool done; bool done;
Todo({ Todo({
int? index, required this.id,
required this.title, required this.title,
required this.createdAt,
this.description = '', this.description = '',
DateTime? createdTime,
this.done = false, this.done = false,
}) : createdAt = createdTime ?? DateTime.now(), });
id = index ?? DbHelper.nextTodoId;
} }

View File

@@ -56,7 +56,12 @@ class _CreateTodoPageState extends State<CreateTodoPage> {
} }
void _onSubmitted() { 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(); Navigator.of(context).pop();
} }
} }

View File

@@ -17,7 +17,7 @@ class DbHelper {
} }
static List<Todo> fetchTodos() => static List<Todo> fetchTodos() =>
_isar.todos.where().doneEqualTo(false).findAll(); _isar.todos.where().doneEqualTo(false).sortByCreatedAtDesc().findAll();
static void addOrUpdateTodo(Todo todo) => static void addOrUpdateTodo(Todo todo) =>
_isar.write((isar) => isar.todos.put(todo)); _isar.write((isar) => isar.todos.put(todo));

View File

@@ -39,7 +39,11 @@ class _TodoListState extends State<TodoList> {
tileColor: Theme.of(context).colorScheme.primaryContainer, tileColor: Theme.of(context).colorScheme.primaryContainer,
title: Text(todo.title), title: Text(todo.title),
trailing: IconButton( trailing: IconButton(
onPressed: () {}, onPressed: () {
todo.done = true;
DbHelper.addOrUpdateTodo(todo);
_showSnackbar(todo);
},
icon: Icon( icon: Icon(
Icons.check_box, Icons.check_box,
color: Theme.of(context).colorScheme.primary, color: Theme.of(context).colorScheme.primary,
@@ -47,4 +51,18 @@ class _TodoListState extends State<TodoList> {
), ),
); );
} }
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);
}),
),
);
}
} }