简体   繁体   中英

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

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

}


@Composable
@Preview
fun VerifyScreenPreview() {
    VerifyScreen("you@re.awesome", 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?

You can use EmptyDestinationsNavigator provided by the library

@Composable
@Preview
fun VerifyScreenPreview() {
    VerifyScreen("you@re.awesome", EmptyDestinationsNavigator)
}

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.

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("you@re.awesome", {}, {}, {})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM