Skip to content

Instantly share code, notes, and snippets.

@ttlg
Created September 5, 2020 06:34
Show Gist options
  • Save ttlg/3dbf3d8e5304710da8b5a6ca2b4c2653 to your computer and use it in GitHub Desktop.
Save ttlg/3dbf3d8e5304710da8b5a6ca2b4c2653 to your computer and use it in GitHub Desktop.
TodosViewController
final todosViewController =
Provider.autoDispose((ref) => TodosViewController(ref.read));
class TodosViewController {
final Reader read;
TodosViewController(this.read);
void initState() async {
read(_todos).state = await read(todoRepository).getTodos();
}
void dispose() {
read(_todos).state.clear();
}
void addTodo(TextEditingController controller) async {
final String text = controller.text;
if (text.trim().isEmpty) {
return;
}
controller.text = '';
final now = DateTime.now();
final newTodo = Todo(text, false, now, "${now.millisecondsSinceEpoch}");
final todos = read(_todos).state..add(newTodo);
await read(todoRepository).saveTodos(todos);
read(_todos).state = todos;
}
void toggleStatus(Todo todo) async {
final todos = read(_todos).state;
final idx = todos.indexWhere((elem) => todo.uid == elem.uid);
if (idx < 0) {
return;
}
todos[idx] = todo.copyWith(done: !todo.done);
await read(todoRepository).saveTodos(todos);
read(_todos).state = todos;
}
void changeSortOrder() {
final SortOrder sortOrder = read(_sortOrder).state;
read(_sortOrder).state =
sortOrder == SortOrder.ASC ? SortOrder.DESC : SortOrder.ASC;
}
}
@ttlg
Copy link
Author

ttlg commented Sep 5, 2020

Pragmatic architecture using Riverpod

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment