Rafael
Rafael

Reputation: 802

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

@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?

Upvotes: 2

Views: 1336

Answers (3)

Risal Fajar Amiyardi
Risal Fajar Amiyardi

Reputation: 1011

You can use EmptyDestinationsNavigator provided by the library

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

Upvotes: 4

Jan Bína
Jan Bína

Reputation: 7208

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.

Upvotes: 1

MMahdi
MMahdi

Reputation: 1

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]", {}, {}, {})
}

Upvotes: 0

Related Questions