Second Midterm Solutions

1. (25 points) The CreateScreen component wants to make a new person and add them to the list of people. The CreateScreen component has state variables that store the name and the office of the new person, but it will need access to the list of people, which is not in the CreateScreen component. The solution to this problem is for the DirectoryApp to prepare a lambda expression that takes the name and the office as parameters and passes them along to the DirectoryApp's createPerson() function, which is capable of creating a new Person and adding them to the list of people. The DirectoryApp can pass that lambda expression to the CreateScreen as a callback function, which is what it does. The DirectoryApp can ithen nvoke the lambda expression from the click handler for the save button. As an added bonus, the createPerson() function that we are now connected to via the lambda expression also has access to the navController, and can issue a command to that controller to navigate back to the list screen.

2. (35 points) We need to change the CreateScreen function to this:

fun CreateScreen(vm : DirectoryModel,
                 goToList:()->Unit,
                 modifier:Modifier)

Then, we need to rewrite the code for the Button at the bottom of the component:

Button(onClick = {
           vm.createPerson(name.value,office.value)
           goToList()
          }) { Text("Save") }

Finally, we need to update the route in the NavHost in the DirectoryApp to

composable(route="create") {
      CreateScreen(
             vm = vm,
             goToList = { navController.navigate("list") },
             modifier = modifier)
}

3. (30 points) We set up the routes like this:

val navController = rememberNavController()
NavHost(navController,startDestination="A") {
        composable(route="A") {
          viewA()
        }
        composable(route="B") {
          viewB(done = { navController.navigate("A") })
        }

}

and define viewB this way:

fun viewB(done:()->Unit) {
   // Other components for viewB go here
   Button(onClick = { done() }) {
     Text("Close")
   }
}