Leave a rating/review
In this episode, you’ll be learning how to save the task to-do list. You’ll be using the ViewModel to save the task to-do list.
Head over to TaskDetailScreen.kt file. At the top of the TaskDetailScreen composable, add the following code:
val viewModel: ListDataManager = viewModel()
var taskTodos by remember {
mutableStateOf(viewModel.readLists().firstOrNull { it.name == taskName }?.tasks ?: emptyList())
}
You create an instance of the ListDataManager class. You’ll use this instance to save the task to-do list. You also have a state variable called taskTodos that you’ll use to display the task to-do list.
Next, scroll to the onFabClick lambda. Add the following code inside the lambda.
viewModel.saveList(TaskList(taskName ?: "", taskTodos + listOf(todoName)))
taskTodos = viewModel.readLists().firstOrNull { it.name == taskName }?.tasks
?: emptyList()
Here, you’re calling the saveList method from the ListDataManager class and passing in the TaskList object. This will save the task to-do list. You’re also updating the taskTodos state variable with the new task to-do list.
Next, you need to display the name of the task at the top app bar. To do this, replace the ”” in the title parameter of ListMakerTopAppBar with the following code:
taskName ?: stringResource(id = R.string.label_task_list)
Create a new resource named label_task_list with the value Task List.
In this code, you’re checking if the taskName is not null, if it’s not null, you’ll display the name of the task. If it’s null, you’ll display Task List.
Next, replace the emptyList() in the TaskDetailsScreenContent and pass your taskTodos state variable.
Lastly, replace the empty lambda in the onBackPress parameter of ListMakerTopAppBar with the following:
onBackPressed
You’re passing in the onBackPressed lambda from the TaskDetailScreen composable. This will navigate the user back to the TaskListScreen composable.
Build and run the app. Tap any task in the list. You navigate to the task detail screen. Tap the floating action button and add a new task to do. You should see the new task to do in the list. You can also see the task name at the top of the app bar. If you press the back button, you’ll be navigated back to the TaskListScreen composable.