为什么它在 Jetpack Compose 中将 NavController 作为 NullPointerException 抛出错误?

why it throw an error for NavController as a NullPointerException in jetpack compose?

我尝试在 android 中学习 jetpack compose,所以我想在一个简单的项目中使用 navController,当我调试项目时它抛出一个错误

NullPointerException when trying to get NavController

for 在这 onClick = {navController.navigate("screenB")} 行代码中。我不知道我在这个项目中错过了什么?我在网上搜索解决了这个问题,但我仍然没有得到它。

  @AndroidEntryPoint
  class NavActivity : ComponentActivity() {
    private lateinit var  viewModel: MyViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = ViewModelProvider(this)[MyViewModel::class.java]
        setContent {
            NavScreen()
        }
    }
}

@Composable
fun NavScreen() {
    val viewModel = hiltViewModel<MyViewModel>()
    val navController = rememberNavController()

    NavHost(navController = navController, startDestination = "screenA") {

        composable(route = "screenA") {
            ScreenA(navController)
        }
        composable(route = "screenB") {
            ScreenB(navController)
        }
      



    }
}

屏幕A:

@AndroidEntryPoint
class ScreenA : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
      
        setContent {
            val navController = rememberNavController()

            ScreenA(navController)
        }
    }
}

@Composable
fun ScreenA(
    navController: NavController
) {
     Button(
            modifier = Modifier
                .width(30.dp)
                .height(15.dp),

            onClick = {
                navController.navigate("screenB")

            },
            colors = ButtonDefaults.buttonColors(
                backgroundColor = Color.Red
            ),
            shape = RoundedCornerShape(20)
        ) {
            Text(
                text = "OK",
              
            )
      }}

屏幕B:

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun ScreenB(
    navController: NavController
) {

}

ScreenS 应该是可组合的,而不是 Activity。尝试在 Screen

中只留下可组合组件
@Composable
fun ScreenA(
  navController: NavController
) {
 Button(
        modifier = Modifier
            .width(30.dp)
            .height(15.dp),

        onClick = {
            navController.navigate("screenB")

        },
        colors = ButtonDefaults.buttonColors(
            backgroundColor = Color.Red
        ),
        shape = RoundedCornerShape(20)
    ) {
        Text(
            text = "OK",
          
        )
  }}