Skip to content

Instantly share code, notes, and snippets.

@ttlg
Created November 21, 2021 12:43
Show Gist options
  • Save ttlg/7d7a66f1160fe50ff9a452b5ad4ece1d to your computer and use it in GitHub Desktop.
Save ttlg/7d7a66f1160fe50ff9a452b5ad4ece1d to your computer and use it in GitHub Desktop.
final todoViewController =
Provider.autoDispose((ref) => TodoViewController(ref.read));
class TodoViewController {
final Reader _read;
TodoViewController(this._read);
Future<void> initState() async {
_read(_todoListState.notifier).state =
await _read(todoRepository).getTodoList();
}
void dispose() {
_read(_todoListState)?.clear();
}
Future<void> addTodo(TextEditingController textController) async {
final String text = textController.text;
if (text.trim().isEmpty) {
return;
}
textController.text = '';
final now = DateTime.now();
final newTodo = Todo(
content: text,
done: false,
timestamp: now,
id: "${now.millisecondsSinceEpoch}",
);
final List<Todo> newTodoList = [newTodo, ...(_read(_todoListState) ?? [])];
_read(_todoListState.notifier).state = newTodoList;
await _read(todoRepository).saveTodoList(newTodoList);
}
Future<void> toggleDoneStatus(Todo todo) async {
final List<Todo> newTodoList = [
...(_read(_todoListState) ?? [])
.map((e) => (e.id == todo.id) ? e.copyWith(done: !e.done) : e)
];
_read(_todoListState.notifier).state = newTodoList;
await _read(todoRepository).saveTodoList(newTodoList);
}
void toggleSortOrder() {
_read(_sortOrderState.notifier).state =
_read(_sortOrderState) == SortOrder.ASC
? SortOrder.DESC
: SortOrder.ASC;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment