androidkotlinandroid-jetpack-composeandroid-jetpackjetpack-compose-modalbottomsheet

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


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
    ) {

    }

}

Solution

  • 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))