I have some program with 2 screens made in Compose. One of this screen have a button that makes transmission to another screen. All works good, if I put only this action on this Button's onClick method. But if I try to add something else, that should be made before changing screen, this navigate function no work anymore.
This way works:
Button(
onClick = onNavigateToListUser
) {
Text(text = "Add")
}
This way does not:
Button(
onClick = {
if (firstName != "" && lastName != "") {
val user = User(uid = 555, firstName, lastName)
userDao.insert(user)
Log.d("MyDebug", ":" user.firstName " " user.lastName)
}
Log.d("MyDebug", "Hey. Second Line")
onNavigateToListUser
}
) {
Text(text = "Add")
}
What is onNavigate...:
composable(route = DatabaseScreens.AddData.name) {
AddDataScreen(
userDao,
onNavigateToListUser = { navController.navigate(DatabaseScreens.UserList.name) }
)
}
Any help would be appreciated.
CodePudding user response:
If you have defined the function doSomething: () -> Unit
, you can use:
onClick = doSomething
onClick = { doSomething() }
In your 2nd case you have to use:
onClick = {
//if () { /* ... */ }
onNavigateToListUser() //instead of onNavigateToListUser
}
CodePudding user response:
In your second code
onClick = {
...
onNavigateToListUser
}
Kotlin's lambda function regards the last line as the returned value, so this one actually returns a lambda function(onNavigateToListUser
) instead of executing it. You need to call it dirictly.
onClick = {
...
onNavigateToListUser()
// or onNavigateToListUser.invoke()
}