Leave a rating/review
You already have an instance of your ViewModel. In this episode, you’ll use it to read and save your todos.
Navigate to TaskListScreen and below your ViewModel instance, add the following code:
val viewModelTasks = taskListViewModel.readLists().toList()
var tasks by remember { mutableStateOf(viewModelTasks) }
Here, you’re creating a variable called viewModelTasks and assigning it the value of the readLists method from your ViewModel. You call toList() on this variable to return an immmutable collection of items. You’re also defining a state variable called tasks and assigning it the value of viewModelTasks. This is because you want to be able to update the tasks once you add new ones and update the view as well.
Next, replace emptyList() with tasks in the TaskListContent composable.
This now enables your TaskListContent to use the tasks from the view model.
Lastly, you need to save your tasks once the user taps Create in the AlertDialog. To do this, replace the // TODO save the task list with:
tasks = (tasks + TaskList(it))
taskListViewModel.saveList(TaskList(it))
In this code, you’re calling the saveList method from your ViewModel and passing in the task list. You’re also updating the tasks state variable with the new task list.
Build and run the app. Tab the floating action button and add a new task. You should see the new task in the list.