我有一个用 Compose 制作的非常简单的应用程序 ui。
目前有 3 个屏幕:登录、项目列表和项目详细信息。
问题是当我单击项目列表中的项目时,我导航到项目详细信息并将项目 ID 作为导航 arg 传递。
问题是,我无法检索它并且参数包是空的。
这是我的代码:
MainActivity
:
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AdrestoApplication()
}
}
}
主要可组合:
@Composable
fun AdrestoApplication() {
val authViewModel = hiltViewModel<AuthViewModel>()
val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState()
val isLoggedIn = authViewModel.isLoggedIn()
val initialRoute =
if (isLoggedIn) Destinations.LISTINGS_LIST else Destinations.LOGIN_ROUTE
val currentRoute = navBackStackEntry?.destination?.route ?: initialRoute
AdrestoTheme {
NavGraph(
navController = navController,
startDestination = currentRoute,
)
}
}
NavGraph
:
object Destinations {
const val LOGIN_ROUTE = "login"
const val HOME_ROUTE = "home"
const val ORDER_DETAILS = "order_details"
const val ORDERS_LIST = "orders_list"
const val LISTING_DETAILS = "listing_details/{listingId}"
const val LISTINGS_LIST = "listings_list"
}
@Composable
fun NavGraph(
navController: NavHostController = rememberNavController(),
startDestination: String = Destinations.LOGIN_ROUTE,
) {
NavHost(navController = navController, startDestination = startDestination) {
composable(Destinations.LOGIN_ROUTE) {
Login(
navController = navController,
)
}
composable(Destinations.LISTINGS_LIST) {
ListingsScreen(
navController = navController,
)
}
composable(
Destinations.LISTING_DETAILS,
arguments = listOf(navArgument("listingId") { type = NavType.LongType })
) {
Log.d("Navhost","NavGraph: the nav arg found is: ${it.arguments!!.getLong("listingId")}") // logs 0
ListingScreen(
navController = navController,
listingId = it.arguments!!.getLong("listingId"),
)
}
}
}
使用参数触发导航的 UI 部分:
LazyColumn(
modifier = Modifier
.padding(all = 8.dp)
.background(MaterialTheme.colors.background)
) {
items(listings.value.data ?: listOf()) { listing ->
Listing(
listing = listing,
onCardClick = {
Log.d("some tag", "ListingsScreen: navigating to ${listing.id}") // logs as expected
val route = "listing_details/${listing.id}"
Log.d("some tag", "ListingsScreen: the route is $route") //logs listing_details/418 (for example)
navController.navigate(route)
},
)
}
}
我不明白这里出了什么问题,不是同一个导航图中的可组合物吗?
我还有另一个问题,当我按下后退按钮时,导航不会上去但它会关闭应用程序(就像没有后退堆栈......)。