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

Jetpack Compose导航在Activity重建后崩溃问题求助

问题分析与解决方案

核心原因

  1. 版本兼容性冲突:你使用的Compose Navigation 2.7.7和lifecycleRuntimeKtx 2.8.4版本不匹配。Navigation 2.7.x系列依赖的Lifecycle版本为2.6.x,高版本Lifecycle的生命周期状态逻辑与旧版Navigation不兼容,导致导航栈条目生命周期状态异常,触发崩溃。
  2. ViewModel与NavController耦合:你的ViewModel直接持有绑定了NavController的lambda,Activity重建后,即使rememberNavController恢复了状态,ViewModel的导航逻辑可能在NavHost完成状态恢复前执行,或因引用问题导致生命周期状态不匹配。

解决方案

1. 对齐依赖版本

将lifecycle相关依赖版本降至Navigation 2.7.7推荐的2.6.2,修改Module级build.gradle:

dependencies {
    // 替换原lifecycle依赖
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.6.2"
    implementation "androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2"
}

2. 解耦ViewModel与NavController

避免在ViewModel中直接绑定NavController的导航逻辑,改用事件流通知UI层处理导航,彻底解耦ViewModel与导航组件:

修改ViewModel

class MyViewModel : ViewModel() {
    private val _navigationEvents = MutableSharedFlow<NavigationEvent>()
    val navigationEvents = _navigationEvents.asSharedFlow()

    fun openScreenB() {
        viewModelScope.launch {
            _navigationEvents.emit(NavigationEvent.NavigateToScreenB)
        }
    }

    sealed class NavigationEvent {
        object NavigateToScreenB : NavigationEvent()
    }
}

修改ScreenA的Composable逻辑

在Composable中收集ViewModel的事件流,处理导航:

composable("ScreenA") {
    val viewModel: MyViewModel = viewModel()
    val navController = rememberNavController()

    LaunchedEffect(Unit) {
        viewModel.navigationEvents.collect { event ->
            when (event) {
                MyViewModel.NavigationEvent.NavigateToScreenB -> {
                    navController.navigate("ScreenB") {
                        launchSingleTop = true
                    }
                }
            }
        }
    }

    ScreenA(
        navigateToScreenB = {
            viewModel.openScreenB()
        }
    )
}

3. 移除手动状态保存逻辑

rememberNavController已经自动处理导航状态的保存与恢复,手动调用navController.saveState()和恢复状态会干扰默认逻辑,导致状态异常,建议直接移除这些操作。

验证步骤

  1. 同步依赖,确保版本对齐
  2. 替换ViewModel和导航逻辑
  3. 测试屏幕旋转、明暗模式切换场景,验证导航功能是否正常

内容的提问来源于stack exchange,提问作者Hilarious Harius

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:04:52