저장 가능한 기본 레시피
이 레시피에서는 구성 변경을 견디는 영구 백 스택을 만드는 기본 예를 보여줍니다.
작동 방식
뒤로 스택을 영구적으로 만들려면 rememberNavBackStack 함수를 사용합니다. 이 함수는 구성 변경 (예: 화면 회전) 시 백 스택을 만들고 기억합니다.
rememberNavBackStack 사용의 요구사항은 탐색 키 (경로)가 직렬화 가능해야 한다는 것입니다. 이 예시에서 RouteA과 RouteB는 @Serializable로 주석이 지정되고 NavKey 인터페이스를 구현합니다.
이 예에서는 entryProvider 내에서 when 문을 사용하여 경로를 해당 컴포저블에 매핑하지만 entryProvider DSL과 함께 사용할 수도 있습니다.
/* * Copyright 2025 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.nav3recipes.basicsaveable import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.lifecycle.compose.dropUnlessResumed import androidx.navigation3.runtime.NavEntry import androidx.navigation3.runtime.NavKey import androidx.navigation3.runtime.rememberNavBackStack import androidx.navigation3.ui.NavDisplay import com.example.nav3recipes.content.ContentBlue import com.example.nav3recipes.content.ContentGreen import com.example.nav3recipes.ui.setEdgeToEdgeConfig import kotlinx.serialization.Serializable @Serializable private data object RouteA : NavKey @Serializable private data class RouteB(val id: String) : NavKey class BasicSaveableActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { setEdgeToEdgeConfig() super.onCreate(savedInstanceState) setContent { val backStack = rememberNavBackStack(RouteA) NavDisplay( backStack = backStack, onBack = { backStack.removeLastOrNull() }, entryProvider = { key -> when (key) { is RouteA -> NavEntry(key) { ContentGreen("Welcome to Nav3") { Button(onClick = dropUnlessResumed { backStack.add(RouteB("123")) }) { Text("Click to navigate") } } } is RouteB -> NavEntry(key) { ContentBlue("Route id: ${key.id} ") } else -> { error("Unknown route: $key") } } } ) } } }