基本 DSL 配方

此方案展示了一个基本示例,说明了如何使用 Navigation 3 API 和两个屏幕,并使用 entryProvider DSL 和持久性返回堆栈。

工作原理

此示例与基本配方类似,但有几个关键区别:

  1. 持久返回堆栈:它使用 rememberNavBackStack(RouteA) 创建并记住返回堆栈。这样一来,即使发生配置更改(例如屏幕旋转),返回堆栈也会保持不变。如需使用 rememberNavBackStack,导航键必须可序列化,因此 RouteARouteB 使用 @Serializable 注释,并实现 NavKey 接口。

  2. entryProvider DSL:此示例未使用 when 语句,而是使用 entryProvider DSL 来定义每个路由的内容。entry<RouteType> 函数用于将路由类型与其可组合项内容相关联。

导航逻辑保持不变:如需从 RouteA 导航到 RouteB,我们将 RouteB 实例添加到返回堆栈。

/*
 * 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.basicdsl

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.navigation3.runtime.NavKey
import androidx.navigation3.runtime.entryProvider
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 BasicDslActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        setEdgeToEdgeConfig()
        super.onCreate(savedInstanceState)
        setContent {
            val backStack = rememberNavBackStack(RouteA)

            NavDisplay(
                backStack = backStack,
                onBack = { backStack.removeLastOrNull() },
                entryProvider = entryProvider {
                    entry<RouteA> {
                        ContentGreen("Welcome to Nav3") {
                            Button(onClick = {
                                backStack.add(RouteB("123"))
                            }) {
                                Text("Click to navigate")
                            }
                        }
                    }
                    entry<RouteB> { key ->
                        ContentBlue("Route id: ${key.id} ")
                    }
                }
            )
        }
    }
}