Skip to content

Split app to 2 screens with Navigation3 and NavigationStack #73

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions Fruitties/androidApp/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,16 @@ plugins {
alias(libs.plugins.androidApplication)
alias(libs.plugins.kotlinAndroid)
alias(libs.plugins.compose.compiler)
alias(libs.plugins.kotlinxSerialization)
}

android {
namespace = "com.example.fruitties.android"
compileSdk = 35
compileSdk = 36
defaultConfig {
applicationId = "com.example.fruitties.android"
minSdk = 26
targetSdk = 35
targetSdk = 36
versionCode = 1
versionName = "1.0"
}
Expand Down Expand Up @@ -79,4 +80,8 @@ dependencies {
implementation(libs.androidx.paging.compose.android)
implementation(libs.androidx.lifecycle.viewmodel.compose)
debugImplementation(libs.compose.ui.tooling)
implementation(libs.androidx.navigation3.runtime)
implementation(libs.androidx.navigation3.ui)
implementation(libs.androidx.lifecycle.viewmodel.navigation3)
implementation(libs.kotlinx.serialization.core)
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,25 @@ import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator
import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.entry
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.runtime.rememberSavedStateNavEntryDecorator
import androidx.navigation3.ui.NavDisplay
import androidx.navigation3.ui.rememberSceneSetupNavEntryDecorator
import com.example.fruitties.android.ui.CartScreen
import com.example.fruitties.android.ui.ListScreen
import kotlinx.serialization.Serializable

@Serializable
data object ListScreenKey : NavKey

@Serializable
data object CartScreenKey : NavKey

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
Expand All @@ -36,9 +53,40 @@ class MainActivity : ComponentActivity() {
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
) {
ListScreen()
NavApp()
}
}
}
}
}

@Composable
fun NavApp() {
val backStack = rememberNavBackStack(ListScreenKey)

NavDisplay(
backStack = backStack,
entryDecorators = listOf(
rememberSceneSetupNavEntryDecorator(),
rememberSavedStateNavEntryDecorator(),
rememberViewModelStoreNavEntryDecorator(),
),
onBack = { keysToRemove -> repeat(keysToRemove) { backStack.removeLastOrNull() } },
entryProvider = entryProvider {
entry<ListScreenKey> {
ListScreen(
onClickViewCart = {
backStack.add(CartScreenKey)
},
)
}
entry<CartScreenKey> {
CartScreen(
onNavBarBack = {
backStack.removeIf { it is CartScreenKey }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using removeIf here will remove all CartScreenKey entries from the back stack. To simply go back to the previous screen, use removeLastOrNull() instead.

Suggested change
backStack.removeIf { it is CartScreenKey }
backStack.removeLastOrNull()

},
)
}
},
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* Copyright 2024 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
*
* https://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.fruitties.android.ui

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.fruitties.android.R
import com.example.fruitties.android.di.App
import com.example.fruitties.viewmodel.CartViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CartScreen(onNavBarBack: () -> Unit) {
// Instantiate a ViewModel with a dependency on the AppContainer.
// To make ViewModel compatible with KMP, the ViewModel factory must
// create an instance without referencing the Android Application.
// Here we put the KMP-compatible AppContainer into the extras
// so it can be passed to the ViewModel factory.
val app = LocalContext.current.applicationContext as App
val extras = remember(app) {
val container = app.container
CartViewModel.creationExtras(container)
}
val viewModel: CartViewModel = viewModel(
factory = CartViewModel.Factory,
extras = extras,
)

val cartState by viewModel.cartUiState.collectAsState()

Scaffold(
topBar = {
CenterAlignedTopAppBar(
navigationIcon = {
IconButton(onClick = onNavBarBack) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = "Navigate back",
)
}
},
title = {
Text(text = stringResource(R.string.frutties))
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.primary,
scrolledContainerColor = MaterialTheme.colorScheme.primary,
navigationIconContentColor = MaterialTheme.colorScheme.onPrimary,
titleContentColor = MaterialTheme.colorScheme.onPrimary,
actionIconContentColor = MaterialTheme.colorScheme.onPrimary,
),
)
},
contentWindowInsets = WindowInsets.safeDrawing.only(
// Do not include Bottom so scrolled content is drawn below system bars.
// Include Horizontal because some devices have camera cutouts on the side.
WindowInsetsSides.Top + WindowInsetsSides.Horizontal,
),
) { paddingValues ->
Column(
modifier = Modifier
// Support edge-to-edge (required on Android 15)
// https://developer.android.com/develop/ui/compose/layouts/insets#inset-size
.padding(paddingValues)
.padding(16.dp),
) {
val cartItemCount = cartState.totalItemCount
Text(
text = "Cart has $cartItemCount items",
modifier = Modifier.padding(8.dp),
)
LazyColumn(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
items(cartState.cartDetails) { cartItem ->
Text(text = "${cartItem.fruittie.name}: ${cartItem.count}")
}
item {
Spacer(
Modifier.windowInsetsBottomHeight(
WindowInsets.systemBars,
),
)
}
}
}
}
}
Loading
Loading