Search code examples
androidnavigationandroid-jetpack-compose

Navigation in Jetpack Compose. Button onClick issue


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.


Solution

  • 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
        }