Home > OS >  How to preview a Composable with non-null type parameters?
How to preview a Composable with non-null type parameters?

Time:02-11

@Composable
fun VerifyScreen(
    email: String,
    navigator: DestinationsNavigator
) {
// .. 

}


@Composable
@Preview
fun VerifyScreenPreview() {
    VerifyScreen("[email protected]", null)
}

Null can not be a value of a non-null type DestinationsNavigator

Of course you can change the type by adding a question mark, but what if that is not an option?

navigator: DestinationsNavigator?

CodePudding user response:

You can use This pattern

@Composable
fun VerifyScreen(
    email: String,
    navigator: DestinationsNavigator
) {
    VerifyScreenContent(
        email = email,
        navigator = {
            //...
        },
        navigator2 = {
            //...
        },
        navigator3 = {
            //...
        },
    )
}

@Composable
fun VerifyScreenContent(
    email: String,
    navigator: () -> Unit,
    navigator2: () -> Unit,
    navigator3: () -> Unit,
) {
// .. 

}


@Composable
@Preview
fun VerifyScreenContentPreview() {
    VerifyScreen("[email protected]", {}, {}, {})
}

CodePudding user response:

It's discouraged to pass NavController or anything like that to your Composables, see the decumentation. If you follow the recommendation, you will simply pass empty lambda (or more of them) from your Preview

Pass lambdas that should be triggered by the composable to navigate, rather than the NavController itself.

The problem with that is when you need a lot of lambdas in your Composable, it doesn't look very nice. One option then is not to preview such a big Composable as a whole but rather preview some smaller pieces of the ui. The other option would be to create some interface for the DestinationsNavigator that you can mock from your previews.

  • Related