Created
September 5, 2020 06:34
-
-
Save ttlg/3dbf3d8e5304710da8b5a6ca2b4c2653 to your computer and use it in GitHub Desktop.
TodosViewController
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pragmatic architecture using Riverpod