android LocalContext.current的问题(@Composable调用只能从@Composable函数的上下文发生)

qjp7pelc  于 2024-01-04  发布在  Android
关注(0)|答案(1)|浏览(288)

我目前正在为我的应用开发主屏幕,但我遇到了一个问题。val context = LocalContext.current行导致了一个错误,该错误指出,“@Composable invocations can only happen from the context of a @Composable function”。您能否提供有关如何解决此问题的指导?为了给予更好的理解,以下是完整的函数:

  1. @Composable
  2. fun HomeScreen(navController: NavController) {
  3. // Use a Box to allow for layering of composables on top of each other
  4. // Used to keep the content at the bottom center of the screen.
  5. Box(
  6. modifier = Modifier
  7. .fillMaxSize()
  8. .padding(16.dp), // Apply padding around the box
  9. contentAlignment = Alignment.BottomCenter // Align content to the bottom center
  10. ) {
  11. // Column to stack buttons vertically
  12. Column(
  13. // Center column contents horizontally
  14. horizontalAlignment = Alignment.CenterHorizontally,
  15. // Space between the column contents
  16. verticalArrangement = Arrangement.spacedBy(8.dp)
  17. ) {
  18. // Button to NAVIGATE TO THE BENEFITS SCREEN
  19. Button(
  20. onClick = { navController.navigate("sleep_benefits") },
  21. // Apply padding to only the top of the first button to push it upwards
  22. modifier = Modifier.padding(bottom = 1.dp)
  23. ) {
  24. Text(text = "Learn About Sleep Benefits")
  25. }
  26. // Button for USER LOGIN
  27. Button(
  28. onClick = { /* TODO: Add navigation to login screen here */ }
  29. ) {
  30. Text(text = "Login to Track Sleep")
  31. }
  32. // New Sign Up Button
  33. Button(
  34. onClick = {
  35. val context = LocalContext.current
  36. context.startActivity(Intent(context, SignInActivity::class.java))
  37. },
  38. modifier = Modifier.padding(top = 8.dp)
  39. ) {
  40. Text(text = "Sign Up")
  41. }
  42. }
  43. }
  44. }

字符串
我试着看这个:Error: "@Composable invocations can only happen from the context of a @Composable function"

j1dl9f46

j1dl9f461#

替换:

  1. // New Sign Up Button
  2. Button(
  3. onClick = {
  4. val context = LocalContext.current
  5. context.startActivity(Intent(context, SignInActivity::class.java))
  6. },
  7. modifier = Modifier.padding(top = 8.dp)
  8. ) {
  9. Text(text = "Sign Up")
  10. }

字符串
使用:

  1. val context = LocalContext.current
  2. // New Sign Up Button
  3. Button(
  4. onClick = {
  5. context.startActivity(Intent(context, SignInActivity::class.java))
  6. },
  7. modifier = Modifier.padding(top = 8.dp)
  8. ) {
  9. Text(text = "Sign Up")
  10. }

展开查看全部

相关问题