android-jetpack-composeandroid-jetpackmaterial3

BottomSheetScaffold won't keep sheetPeekHeight when navigate back (Jetpack Compose)


According to AndroidX Compose Material 3 example, this BottomSheetScaffold has peekHeight = 128dp. At this time, it only has two state: Expanded and PartiallyExpanded. When I navigate to another screen then navigate back, the BottomSheetScaffold seem to lose its peekHeight and now it can be Hidden. I have my solution but it's not exactly what I want. How can I keep peekHeight in this situation?

Here is my code

@ExperimentalMaterial3Api
@Composable
fun ScreenA(
    navController: NavController
) {
    val scaffoldState = rememberBottomSheetScaffoldState(
        bottomSheetState = rememberStandardBottomSheetState(
            initialValue = SheetValue.Expanded,
            confirmValueChange = {
                it != SheetValue.Hidden  // Prevent collapsing but not what I want
            }
        )
    )

    BottomSheetScaffold(
        scaffoldState = scaffoldState,
        sheetPeekHeight = 128.dp,
        sheetContent = {
            Box(
                Modifier
                    .fillMaxWidth()
                    .height(128.dp),
                contentAlignment = Alignment.Center
            ) {
                Text("Swipe up to expand sheet")
            }
            Column(
                Modifier
                    .fillMaxWidth()
                    .padding(64.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text("Sheet content")
                Spacer(Modifier.height(20.dp))
                Button(
                    onClick = {
                        navController.navigate("ScreenB") // navigate to another screen
                    }
                ) {
                    Text("Click to collapse sheet")
                }
            }
        }) { innerPadding ->
        Box(Modifier.padding(innerPadding)) {
            Text("Scaffold Content")
        }
    }
    LaunchedEffect(scaffoldState.bottomSheetState.currentValue) {
        println(scaffoldState.bottomSheetState.currentValue) // check scaffold state
    }
}

Solution

  • This should help:

     val scaffoldSheetState = rememberBottomSheetScaffoldState(
            SheetState(
                skipHiddenState = true,
                skipPartiallyExpanded = false,
                initialValue = SheetValue.PartiallyExpanded
            )
        )
    

    From the docs: skipHiddenState - Whether the hidden state should be skipped. If true, the sheet will always expand to the Expanded state and move to the PartiallyExpanded if available, either programmatically or by user interaction.