raamcosta / compose-destinations

Annotation processing library for type-safe Jetpack Compose navigation with no boilerplate.
https://composedestinations.rafaelcosta.xyz
Apache License 2.0
3.21k stars 132 forks source link

pass navController to DestinationsNavHost #159

Closed periva101 closed 2 years ago

periva101 commented 2 years ago

I want to from compose-destinations to navigation component, I am thinking to pass navController to compose, but how to pass from nav controller to DestinationsNavHost or I want to pass my navController from fragment to compose destination function

raamcosta commented 2 years ago

Hi @periva101 👋

To be honest, I would encourage you not to mix two navigation libraries in the same project unless you absolutely need to. If you're using fragment-based jetpack navigation, then use that also for screens you implement with Compose. You can o that by wrapping the Composable function in a Fragment and navigating to that fragment with normal navigation.

Really I would only recommend jetpack compose navigation or compose destinations to apps where all navigation is done by this.

NOW, if you still want to do this, you need to be careful because both Compose Destinations and jetpack navigation have NavControllers, so you need to use the correct one everytime considering where you want to navigate to. The way you can pass the fragment based navcontroller to your Composable @Destinations is this:

https://composedestinations.rafaelcosta.xyz/destination-arguments/navhost-level-parameters#use-dependenciescontainerbuilder-to-prepare-dependencies

Now in this case, you cannot pass it as a NavController because that type is already a type that Compose Destinations knows how to provide. So it will think you want the nav controller from DestinationsNavHost instead of the one from fragment based navigation. Given this, I would create a wrapper to the nav controller coming from fragment, like this:

class FragmentBasedNavController(val navController: NavController)

//.... and then

DestinationsNavHost(
//...
    dependenciesContainerBuilder = {
        dependency(FragmentBasedNavController(yourNavControllerComingFromFragment))
    }
)

// and then on your Composables where you need this nav controller:

@Destination
@Composable
fun YourScreen(
    //...
    fragmentNavController: FragmentBasedNavController
) {
    //.... for exemple on some click button:
    fragmentNavController.navController.navigate(R.id.destinationIdFromYourNavGraphXml)
}

I'll close this but let me know how this goes for you 🙂

ghost commented 2 years ago

your support is better than jetpack compose team , thank you very very much