'Sheet of BottomSheetScaffold automatically expands on recomposition

In Jetpack Compose, I have a BottomSheetScaffold with some content. This content is observed from the ViewModel, like this:

BottomSheetScaffold(
    sheetContent = { SheetContent(sheetData = viewModel.sheetData) }
) {}

So whenever viewModel.sheetData changes, a recomposition is triggered. Whenever this happens, the bottom sheet automatically expands. Is this a bug or a feature? Can I disable this? I am using the newest version: 1.1.0-alpha01

Edit: Here is an example using LaunchedEffect instead of a ViewModel.

@OptIn(ExperimentalMaterialApi::class)
@Preview
@Composable
fun HomeScreen() {
    var addSheetData by remember { mutableStateOf(false) }

    LaunchedEffect(true) {
        delay(2000)
        addSheetData = true
    }

    BottomSheetScaffold(sheetContent = {
        if (addSheetData) {
            Column {
                Text(text = "Text1", fontSize = 36.sp)
                Text(text = "Text2", fontSize = 36.sp)
                Text(text = "Text3", fontSize = 36.sp)
                Text(text = "Text4", fontSize = 36.sp)
                Text(text = "Text5", fontSize = 36.sp)
            }
        }
    }, sheetBackgroundColor = Color.LightGray) {}
}

The sheet with the 5 texts expands automatically.



Solution 1:[1]

It seems a bug.
Currently (1.0.x and 1.1.0-alpha01) it happens when the sheetContentHeight < sheetPeekHeight.
In this case the scaffoldState.bottomSheetState result expanded also if the content sheet is not displayed.

You can easily verify it using in your code:

sheetBackgroundColor = if (scaffoldState.bottomSheetState.isCollapsed) Color.LightGray else Color.Yellow

When addSheetData == false the background color becomes Yellow. When you recompose the composable, since the state is expanded, the content sheet is full expanded.

As workaround you can use something like:

  sheetContent = { 
        if (!addSheetData){
            Box(Modifier.fillMaxWidth().height(60.dp))
        }    

        if (addSheetData) {
            Column {
                Text(text = "Text1", fontSize = 36.sp)
                Text(text = "Text2", fontSize = 36.sp)
                Text(text = "Text3", fontSize = 36.sp)
                Text(text = "Text4", fontSize = 36.sp)
                Text(text = "Text5", fontSize = 36.sp)
            }
        }
  }

Solution 2:[2]

Try adding an initial value:

val bottomSheetScaffoldState = rememberBottomSheetScaffoldState(
        bottomSheetState = BottomSheetState(
            initialValue = BottomSheetValue.Collapsed,
        )
    )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabriele Mariotti
Solution 2 Fusion Developers