Home > front end >  Back button does not work correctly with NavOptions setPopUpTo
Back button does not work correctly with NavOptions setPopUpTo

Time:11-13

I have fragment with list of notes. When user clicks on a note, they open fragment with note page. I use navigation UI and NavOptions to navigate:

    fun toNotePage() {
        val navOptions: NavOptions = NavOptions.Builder()
            .setPopUpTo(R.id.navigation_notes, true, true)
            .setRestoreState(true)
            .build()

        findNavController().navigate(R.id.navigation_note_page, null, navOptions)
    }

At first I used .setPopUpTo(R.id.navigation_notes, false, true), with "inclusive" param false. That time I pressed on the note, note page fragment opened correctly, but back button didn't work. Than I changed "inclusive" param to true, and back button worked in the note page fragment, but only once. When I return with back button to notes list and than click on the note once more, I navigate to note page fragment, but back button stops working. And system back button closes application insteam of opening notes list.

CodePudding user response:

I guess you want the default behavior but confusing the system with adding navOptions. Just delete them and only use single line:

    fun toNotePage() {
        findNavController().navigate(R.id.navigation_note_page)
    }

CodePudding user response:

This was not a navigation issue at all. I just used StateFlow to trigger navigation after list item clicked, but I did not update it correctly. So I did return to notesFragment, but I was always redirected to notes once more.

https://developer.android.com/topic/architecture/ui-layer/events

  • Related