androidkotlinandroid-jetpack-composenavigation-drawer

ModalNavigationDrawer doesn't want to close or open programmatically but responds to swipes


I followed Android's Compose tutorial and copied the code to open and close the drawer, but I cannot get it to programmatically open or close. It swipes just fine, but I'd like it to close when I tap a button:

@Composable
fun MainScreenWithNavigationDrawer() {
    val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
    val scope = rememberCoroutineScope()

    ModalNavigationDrawer(
        drawerContent = {
            ModalDrawerSheet {
                NavigationDrawerItem(
                    label = { Text(text = "Load trivia file") },
                    selected = false,
                    onClick = {
                        scope.launch {
                            drawerState.close()
                        }
                        println("CLICK")
                    },
                )
            }
        },
    ) {
        // Screen content
    }
}

When I click the button I do see "CLICK" in my logcat but the drawer does not close.

What am I missing?


Solution

  • Although you create a DrawerState with

    val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
    

    you never pass it to the ModalNavigationDrawer. Therefore the ModalNavigationDrawer creates its own state, and what you do with your state has no effect.

    Simply add this parameter to ModalNavigationDrawer:

    drawerState = drawerState,
    

    Now your state can control the ModalNavigationDrawer, and everything should work as expected.