Jetpack Compose NavGraphBuilder 使用可组合作为方法参数。怎么办?

问题描述 投票:0回答:1

这是来自 https://github.com/AkarshGuptaa/Compass.git 的 Android 指南针应用程序项目,它编译和运行没有错误

我想知道 compassComposable: @Composable () -> 当对该函数的任何调用都没有提供“compassComposable”参数时,单位如何传递给 HomeScreen 可组合函数

这是部分代码

NavHost(
    modifier = modifier,
    navController = navController,
    startDestination = startDestination,
){
    composable(ScreenRoutes.Home.name){
        HomeScreen( // <- call to home screen (without compassComposable parameter)
        degrees = degrees,
        isMagneticFieldSensorPresent = isMagneticFieldSensorPresent,
        onMenuClick = { navController.navigate(ScreenRoutes.WidgetSelection.name )}
        ){..}
        ..       
    }

    composable(ScreenRoutes.WidgetSelection.name){ // but somehow this is correctly passed to the HomeScreen composable function HOW??
        ..
        WidgetScreen( ..
        )
    }
}

But the HomeScreen Composable fun has a compassComposable parameter that is never supplied.

@Composable
fun HomeScreen(
     modifier: Modifier = Modifier,
     degrees: Int, // observe this
     isMagneticFieldSensorPresent: Boolean,
     onMenuClick: () -> Unit = {},
     compassComposable: @Composable () -> Unit // Correctly points to the right navGraph composable but since it is never passed to the function when called, how does this happen?? 
     )  {
        ...
        compassComposable() // correctly displays the selected compass widget
        ..
        }


I've tried to trace it through the debugger but the "magic" seems to be happening in the background
android navigation parameter-passing composable navgraph
1个回答
0
投票

借助 Kotlin 上的尾随 lambda 语法,这成为可能

尾随 lambda 顾名思义,是一个 lamda 函数,它是函数中的最后一个(尾随)参数

所以,假设你有一个函数

foo

fun foo(a:Int, b:Int, c:()->Unit){
   // Do something
}

如果您注意到,我们有一个 lambda 函数作为最后一个参数,所以您可以像这样调用它,对吧?

fun main(){
  foo(a= 1, b=2 ,c ={
       // Do something 
        })
}

您可以通过尾随 lambda 语法使其在视觉上更易于阅读,如下所示

fun main(){
  foo(a=1, b=2){
    // This is provided to the parameter C 

    // Do something 
  }
}

可以在这里

找到有关文档的详细阅读内容
© www.soinside.com 2019 - 2024. All rights reserved.