-
Hi! Is there a best/recommended way to use Decompose while using a Navigation Drawer with Compose? Thanks, JP! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Thanks for the question! There are no recommendations. The Compose navigation drawer is controlled by the The first approach is the most simple one - if you don't need any special logic, like closing the drawer on back button click. In this case you can just keep everything on the UI side, and so your business logic (Decompose components) is not involved. @Composable
fun SomeContent(some: Some) {
val scaffoldState = rememberScaffoldState()
val scope = rememberCoroutineScope()
Scaffold(
scaffoldState = scaffoldState,
drawerContent = { Text("Drawer content") }
) {
Button(
onClick = {
scope.launch {
scaffoldState.drawerState.open()
}
}
) { Text("Open drawer") }
}
} Another approach is when you need to control the drawer by the business logic. In this case you need to have the drawer opened state as part of the component's state, and it should be the source of the truth. The interface Some {
val models: Value<Model>
fun setDrawerState(isOpen: Boolean)
data class Model(
val isDrawerOpen: Boolean
)
}
@Composable
fun Foo(some: Some) {
val model by some.models.subscribeAsState()
val isDrawerOpen = model.isDrawerOpen
val drawerState =
rememberDrawerState(
initialValue = if (isDrawerOpen) DrawerValue.Open else DrawerValue.Closed,
confirmStateChange = {
some.setDrawerState(
when (it) {
DrawerValue.Closed -> false
DrawerValue.Open -> true
}
)
true
}
)
LaunchedEffect(isDrawerOpen) {
if (isDrawerOpen) {
drawerState.open()
} else {
drawerState.close()
}
}
val scaffoldState = rememberScaffoldState(drawerState = drawerState)
Scaffold(
scaffoldState = scaffoldState,
drawerContent = { Text("Drawer") }
) {
Button(onClick = { some.setDrawerState(isOpen = true) }) {
Text("Open drawer")
}
}
} |
Beta Was this translation helpful? Give feedback.
Thanks for the question! There are no recommendations. The Compose navigation drawer is controlled by the
DrawerState
, please see the corresponding docs. I see two different approaches when combining the drawer with Decompose.The first approach is the most simple one - if you don't need any special logic, like closing the drawer on back button click. In this case you can just keep everything on the UI side, and so your business logic (Decompose components) is not involved.