me.at.coding
me.at.coding

Reputation: 17786

Navigation component: how to list the fragments on the back stack?

For debugging purposes I need to know which Fragments (I need the class names like MyCoolFragment) are on the back stack and in which order they are on the back stack. How can I do that when using the Navigation component?

I hoped for something like this:

findNavController().backStack.forEach {
    // print it.toString()
}

but when I try to use this, Android Studio tells me

enter image description here

So, how can I watch what's on the back stack? I am currently working with 2.3.0-alpha04, in case it matters.

Upvotes: 0

Views: 2774

Answers (2)

Tatsuya Fujisaki
Tatsuya Fujisaki

Reputation: 2001

For debugging purposes, you can ignore the lint error and list non-NavGraph destinations on the back stack.

val breadcrumb = navController
    .currentBackStack
    .value
    .map {
        it.destination
    }
    .filterNot {
        it is NavGraph
    }
    .joinToString(" > ") {
        it.displayName.split('/')[1]
    }

// e.g. first_fragment > second_fragment > third_fragment

Upvotes: 3

ianhanniballake
ianhanniballake

Reputation: 200110

That isn't available at runtime. It is only possible when using the TestNavHostController class as part of the navigation-testing artifact as a way of verifying your back stack as part of a test.

Upvotes: 1

Related Questions