5. 将查询连接到UI
在本章中,您将要显示一系列启动 站点在一个 LazyColumn.
配置LaunchListAdapter
在LaunchList
中,声明一个空的LaunchListQuery.Launch
列表:
app/src/main/java/com/example/rocketreserver/LaunchList.kt
@Composablefun LaunchList(onLaunchClick: (launchId: String) -> Unit) {var launchList by remember { mutableStateOf(emptyList<LaunchListQuery.Launch>()) }
LaunchListQuery.Launch
是从您的LaunchList生成的类型安全生成模型。
为项目创建UI
更新LaunchItem
composable,将其传递一个LaunchListQuery.Launch
并显示ID:
app/src/main/java/com/example/rocketreserver/LaunchList.kt
@Composableprivate fun LaunchItem(launch: LaunchListQuery.Launch, onClick: (launchId: String) -> Unit) {ListItem(modifier = Modifier.clickable { onClick(launch.id) },headlineText = {// Mission nameText(text = "Launch ${launch.id}")},
使用列表中的数据
填充launchList
,使用响应中的数据,并在LazyColumn中使用它:
app/src/main/java/com/example/rocketreserver/LaunchList.kt
@Composablefun LaunchList(onLaunchClick: (launchId: String) -> Unit) {var launchList by remember { mutableStateOf(emptyList<LaunchListQuery.Launch>()) }LaunchedEffect(Unit) {val response = apolloClient.query(LaunchListQuery()).execute()launchList = response.data?.launches?.launches?.filterNotNull() ?: emptyList()}LazyColumn {items(launchList) { launch ->LaunchItem(launch = launch, onClick = onLaunchClick)}}}
注意:因为在架构定义中launches
是可为空的Launch对象列表。
测试您的查询
点击运行按钮。现在您的UI已与GraphQL查询相连 🚀
外观有点单调。接下来,您将为列表添加更多信息,使其看起来更美观!