7

I am trying to learn Jetpack compose but I have an issue with the preview. I have this composable.

fun RegistrationScreen(
    state: RegisterState,
    onRegister: (String, String, String, String) -> Unit,
    onBack: () -> Unit,
    onDismissDialog: () -> Unit
) { //Code }
@Preview(showBackground = true)
@Composable
private fun DefaultPreview() {
    RegistrationScreen(
        state = RegisterState(),
        onRegister = "Name",
        onBack = { },
        onDismissDialog = { }
    )
}

Obviously this is the problem in onRegister

Type mismatch: inferred type is String but (String, String, String, String) -> Unit was expected

But I can't pass these Strings parameters together and I don't know why.

For extra context, this is my NavGraphBuilder:

fun NavGraphBuilder.addRegistration(
    navController: NavHostController
){
    composable(route = Destinations.Register.route) {
        val viewModel: RegisterViewModel = hiltViewModel()
        RegistrationScreen(
            state = viewModel.state.value,
            onRegister = viewModel::register,
            onBack = {
                navController.popBackStack()
            },
            onDismissDialog = viewModel::hideErrorDialog
        )
    }

And this my ViewModel:

class RegisterViewModel : ViewModel() {
    val state: MutableState<RegisterState> = mutableStateOf(RegisterState())
    fun register(
        name: String,
        email: String,
        password: String,
        confirmPassword: String
    ) { //code }
2
  • 1
    what do you mean by "I can't pass these Strings parameters together"? It should be a closure, e.g. onRegister = {}, instead of onRegister = "Name",, but as it has multiple parameters, you have to name them, for example onRegister = { _, _, _, _, -> }, Commented Feb 2, 2022 at 15:14
  • 1
    I didn't know I had to do it in that way. I thought I should pass parameters. This fixed the problem. Thanks a lot. Commented Feb 2, 2022 at 15:54

1 Answer 1

13

You have to write something like this to make it works

@Preview(showBackground = true)
@Composable
private fun DefaultPreview() {
    RegistrationScreen(
        state = RegisterState(),
        onRegister = { _, _, _, _ -> },
        onBack = { },
        onDismissDialog = { }
    )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.