name: portada class: portada-slide, center, middle # Compose ### Navigation --- # Requisits - sealed & object ``` private sealed interface MyInterface { data object MyObject : MyInterface data class MyDataClass(val someAtt: String) : MyInterface } ``` --- # Requisits - state hoisting ``` @Composable fun MainComposable(){ val text = remember{ mutableStateOf("") } Text(text.value) MyTextField(text.value, {text.value = it}) } @Composable fun MyTextField(text: String, onValueChanged: (String)-> Unit){ Card{ TextField(text, onValueChange = onValueChanged) } } ``` --- # Navegació - Navegar entre diferents pantalles --- # Pantalles ``` @Composable fun Screen1(navigateToScreen2: ()-> Unit){ Button(onClick = navigateToScreen2){ Text("Go To screen2") } } @Composable fun Screen2(navigateToScreen3: (String)-> Unit){ var text by remember{ mutableStateOf("") } TextField(text, onValueChange = {text = it}) Button(onClick = {navigateToScreen3(text)}){ Text("Go to Screen 3") } } @Composable fun Screen3(message: String){ Text(message) } ``` --- # Navegació - Manual - Podem definir la pantalla actual com un estat - Modificar el valor, indica mostrar una pantalla nova --- # Definir pantalles ``` private sealed interface Screen { data object Screen1 : Screen data object Screen2 : Screen data class Screen3(val message: String) : Screen } ``` --- # ViewModel ``` private class ManualNavAppViewModel : ViewModel() { val currentScreen = mutableStateOf
(Screen.Screen1) fun navigateTo(screen: Screen) { currentScreen.value = screen } } ``` --- # Composable ``` @Composable fun ManualNav() { val viewModel = viewModel { ManualNavAppViewModel() } val currentScreen = viewModel.currentScreen.value when (currentScreen) { Screen.Screen1 -> Screen1( navigateToScreen2 = { viewModel.navigateTo(Screen.Screen2) } ) is Screen.Screen2 -> Screen2( navigateToScreen3 = { viewModel.navigateTo(Screen.Screen3(it)) } ) is Screen.Screen3 -> Screen3(currentScreen.message) } } ``` --- # Exercicis Exercici navegació manual --- # Navegació Jetpack - Hi ha una llibreria que ens ajuda a la navegació --- # Definició de destins ``` object Destination { @Serializable data object Screen1 @Serializable data object Screen2 @Serializable data class Screen3(val message: String) } ``` - L'object Destination és per organització --- # Composable ``` @Composable fun LibNavScreenSample() { val navController = rememberNavController() NavHost(navController = navController, startDestination = Destination.Screen1) { composable
{ Screen1( navigateToScreen2 = { navController.navigate(Destination.Screen2) }, ) } composable
{ Screen2 { navController.navigate(Destination.Screen3(it)) } } composable
{ backStack -> val message = backStack.toRoute
().message Screen3(message) } } } ```