You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose中BottomSheet从屏幕顶部弹出问题如何修复?

BottomSheet从顶部滑出异常修复方案

问题根因

异常动画由以下两处代码逻辑共同导致:

  1. 初始化BottomSheetState时直接指定初始值为BottomSheetValue.Expanded,同时设置了sheetPeekHeight = 0.dp。组件首次渲染时会先渲染折叠状态(高度为0),再跳转到展开状态,系统计算动画路径时出现偏差,就会出现从顶部滑下的异常效果。
  2. 未禁用BottomSheet的默认初始状态过渡动画,首次渲染的状态切换触发了错误的动画逻辑。

修复步骤

  • 修改BottomSheetState初始值为BottomSheetValue.Collapsed,避免初始化直接触发展开状态渲染
  • 添加LaunchedEffect副作用,在组件首次挂载完成、布局计算结束后,再主动调用展开方法,此时动画路径会正确从底部计算

修复后完整代码

@ExperimentalMaterialApi
@Composable
fun BottomSheet(
    modifier: Modifier = Modifier,
    buttonText: String,
    composable: @Composable () -> Unit,
    scope: CoroutineScope
) {
    val bottomSheetScaffoldState = rememberBottomSheetScaffoldState(
        // 初始状态改为折叠
        bottomSheetState = BottomSheetState(BottomSheetValue.Collapsed)
    )
    // 新增副作用,首次渲染完成后自动展开
    LaunchedEffect(Unit) {
        bottomSheetScaffoldState.bottomSheetState.expand()
    }
    BottomSheetScaffold(
        scaffoldState = bottomSheetScaffoldState,
        sheetContent = {
            Column(
                Modifier
                    .fillMaxWidth()
                    .height(200.dp)
                    .padding(8.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
              
                Button(colors = ButtonDefaults.buttonColors(
                    backgroundColor = AppColor.brandColor.BLUE_DE_FRANCE,
                    contentColor = AppColor.neutralColor.DOCTOR
                ),
                    shape = RoundedCornerShape(
                        small
                    ),
                    onClick = {
                        scope.launch {
                            bottomSheetScaffoldState.bottomSheetState.collapse()
                        }
                    }) {
                    Text(buttonText)
                }
            }
        },
        sheetPeekHeight = 0.dp,
        sheetShape = RoundedCornerShape(topEnd = medium, topStart = medium)
    ) {
        composable()
    }
}

额外优化说明

如果不需要BottomSheet的滑入动画,可以在初始化BottomSheetState时指定animationSpec = SnapSpec(),直接跳过动画,也能解决该问题。


内容的提问来源于stack exchange,提问作者Saeed Noshadi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:45:06