Jetpack Compose 导航在方向更改后导致应用程序崩溃

问题描述 投票:0回答:1

我在我的应用程序中使用 Jetpack Compose Navigation。
撰写导航版本:2.7.7
生命周期RuntimeKtx:“2.8.4”
Kotlin 版本:1.9.25
设备:小米220333QNY
我有 3 个屏幕:A、B、C
导航图看起来像
A⟷B⟷C
其中 → 是导航(路线)
← 是 navigationUp() 或硬件后退按钮。
setContent {
    val navController = rememberNavController()
    NavHost(
        navController = navController,
        ...
    ) { ... }
}

一切正常,直到重新进行活动(方向改变或切换亮/暗模式)。休闲路线后

val navController = rememberNavController()
再次打电话。 NavController 重新创建,现在 navigateUp() 不执行任何操作,硬件恢复工作并且导航(路由)因错误导致应用程序崩溃

java.lang.IllegalStateException: State must be at least CREATED to move to DESTROYED, but was INITIALIZED in component NavBackStackEntry(2d8f0727-c13b-4635-ac94-f279608c3cfc) destination=Destination(0x67884f5a) route=Editor
    at androidx.lifecycle.LifecycleRegistry.moveToState(LifecycleRegistry.jvm.kt:131)
    at androidx.lifecycle.LifecycleRegistry.setCurrentState(LifecycleRegistry.jvm.kt:107)
    at androidx.navigation.NavBackStackEntry.updateState(NavBackStackEntry.kt:186)
    at androidx.navigation.NavBackStackEntry.setMaxLifecycle(NavBackStackEntry.kt:159)
    at androidx.navigation.NavController.updateBackStackLifecycle$navigation_runtime_release(NavController.kt:1100)
    at androidx.navigation.NavController.dispatchOnDestinationChanged(NavController.kt:996)
    at androidx.navigation.NavController.navigate(NavController.kt:1882)
    at androidx.navigation.NavController.navigate(NavController.kt:1817)
    at androidx.navigation.NavController.navigate(NavController.kt:2225)
    at androidx.navigation.NavController.navigate$default(NavController.kt:2220)
    at ...

我尝试使用 saveState = true、restoreState = true、launchSingleTop = true 属性进行导航,但这并不能解决问题。 我还尝试在rememberNavController之后在onSaveInstanceState和restoreState(bundle)中使用navController saveState(),但它也没有帮助。
我很感激任何帮助。
谢谢!

android kotlin navigation android-jetpack-compose
1个回答
0
投票

重新创建 Activity 时,NavController 也会重新创建,丢失之前的返回堆栈状态。

NavBackStackEntry 生命周期状态似乎不正确(例如,从 INITIALIZED 转换到 DESTROYED),这会导致崩溃。

您可以进行以下更改:

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        setContent {
            MyApp(savedInstanceState)
        }
    }
}

@Composable
fun MyApp(savedInstanceState: Bundle?) {
    val navController = rememberSaveable(saver = NavControllerSaver()) {
        rememberNavController()
    }

    NavHost(
        navController = navController,
        startDestination = "screenA"
    ) {
        composable("screenA") {  }
        composable("screenB") {  }
        composable("screenC") {  }
    }
}

@Composable
fun rememberNavControllerWithState(savedInstanceState: Bundle?): NavHostController {
    val navController = rememberNavController()

    savedInstanceState?.let {
        navController.restoreState(it)
    }

    return navController
}
© www.soinside.com 2019 - 2024. All rights reserved.