BottomSheetScaffold fails to open when the screen rebuilds. Only opens when I click anywhere on the screen

1.1k Views Asked by At

I need to blur the background of the screen when the BottomSheetScaffold is expanded but when I change a remembered value before expanding the bottom sheet, the bottom sheet fails to open on the first try. Only it opens when I click somewhere on the screen. How to avoid this?

@Composable
fun MyScreen() {


   val sheetState = SheetState(skipHiddenState = false, skipPartiallyExpanded = false)

   val sheetController = rememberBottomSheetScaffoldState(sheetState)

   var isBlurred by remember {
        mutableStateOf(false)
    }

    val blur by animateDpAsState(targetValue = if (isBlurred) 10.dp else 0.dp)

    val scope = rememberCoroutineScope()

   Box (modifier = Modifier.blur(radius = blur).fillMaxSize()) {

      ElevatedButton(onClick = {

          scope.launch {

              isBlurred = true
              sheetController.bottomSheetState.expand() // Fails to expand.

          }
        
      }) {
          
          Text("Blur")

      }

}

   BottomSheetScaffold(
        scaffoldState = sheetController,
        sheetContent = {
           // My Content
        },
        sheetDragHandle = {},
        sheetContainerColor = Color.Transparent,
        sheetShadowElevation = 0.dp,
        sheetSwipeEnabled = false
    ) {

    }

}
2

There are 2 best solutions below

0
On BEST ANSWER

It turned out I have to remember the SheetState as well because during recomposition the SheetState(skipHiddenState = false, skipPartiallyExpanded = false) is not maintained during recomposition will be done on the next recomposition. I thought the rememberBottomSheetScaffoldState would do it automatically but no. I had to edit the code to either

val sheetState = remember { SheetState(skipHiddenState = false, skipPartiallyExpanded = false) }

val sheetController = rememberBottomSheetScaffoldState(sheetState)

Or merge it together as:

val sheetController = rememberBottomSheetScaffoldState(SheetState(skipHiddenState = false, skipPartiallyExpanded = false))

1
On

The issue you're experiencing is likely due to the fact that you're trying to modify the state isBlurred and immediately expand the BottomSheetScaffold within the same coroutine scope. This can cause a race condition where the BottomSheetScaffold doesn't have enough time to process the state change before it attempts to expand.

You can give some delay after changing the mutableState delay(200)