Home > Enterprise >  How we can use bottom sheet in jetpack compose?
How we can use bottom sheet in jetpack compose?

Time:01-29

I am start to migrate my project to jetpack compose, and I am learning jetpack compose now, I want to use bottom sheet in my project, I search on internet to use bottom sheet, I find some codes, I use it in my app, every things looks good, but when I run the my app, it crashed, I am not sure where I mistake? Is there any other solution?

    class MyActivity : ComponentActivity() {
    @ExperimentalMaterialApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {

            ModalBottomSheetLayoutScreen()
        }
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun ModalBottomSheetLayoutScreen() {
    val modalBottomSheetState = rememberModalBottomSheetState(initialValue = 
  ModalBottomSheetValue.Hidden)
    val scope = rememberCoroutineScope()
    ModalBottomSheetLayout(
        sheetContent = {

        },
        sheetState = modalBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
        sheetBackgroundColor = colorResource(id = R.color.white),
        // scrimColor = Color.Red,  // Color for the fade background when you open/close the drawer
    ) {
        Scaffold(

            backgroundColor = colorResource(id = R.color.white)
        ) {
            MyScreen(scope = scope, state = modalBottomSheetState)
        }
    }
}


@OptIn(ExperimentalMaterialApi::class)
@Composable
fun MyScreen(
    scope: CoroutineScope, state: ModalBottomSheetState
) {

        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
           

                Column(
                    modifier = Modifier
                        .width(170.dp),
                    horizontalAlignment = Alignment.CenterHorizontally

                    ) {
                  
                        Text(
                            text = "click",
                            modifier = Modifier
                                .clickable {
                                    scope.launch {
                                        state.show()
                                    }
                              }  
                        )}} }

   
@Preview(showBackground = true)
@Composable
fun ModalBottomSheetLayoutScreenPreview() {
    ModalBottomSheetLayoutScreen()
}

CodePudding user response:

It crashes because your sheetContent is empty. I've reported this bug. In a real app you should have some content, otherwise you don't need ModalBottomSheetLayout at all.

Specifying any view inside sheetContent solves the problem.

  •  Tags:  
  • Related