Передача аргументов в графе вложенной навигации JETPACK COMPOSE

Я пытаюсь передать имя из LoginPage в HomePage, но не могу этого добиться. Я пробовал много вещей, но все они были неправильными. Я новичок в Android, и сейчас я очень запутался.

Это мой ROOTGRAPH

      @Composable
fun RootNavigationGraph(navController: NavHostController) {
    NavHost(
        navController = navController,
        route = Graph.ROOT,
        startDestination = Graph.AUTHENTICATION
    ) {
        authNavGraph(navController = navController)
        composable(route = Graph.HOME) {
            MainScreen()
        }
    }
}

object Graph {
    const val ROOT = "root_graph"
    const val AUTHENTICATION = "auth_graph"
    const val HOME = "home_graph"
}

Это мой ГРАФИК АУТЕНТИФИКАЦИИ

      fun NavGraphBuilder.authNavGraph(navController: NavHostController){
    navigation(
        route = Graph.AUTHENTICATION,
        startDestination = AuthScreen.OptionHome.route
    ){
        composable(route = AuthScreen.OptionHome.route) {
            Option(
                onClick = {
                    navController.popBackStack()
                    navController.navigate(AuthScreen.LogIn.route)
                },
                onRegisterClick = {
                    navController.navigate(AuthScreen.Register.route)
                },
                onGuestClick = {
                    navController.navigate(Graph.HOME)
                }
            )
        }
        composable(route = AuthScreen.LogIn.route){
            LoginPage(
                onLoginClick = {
                    navController.navigate(Graph.HOME)
                }
            )
                
        }
        composable(route = AuthScreen.Register.route){
            RegisterPage(
                onSignInClick = {
                    navController.navigate(AuthScreen.LogIn.route)
                }
            )
        }
    }
}

sealed class AuthScreen(val route: String){
    object OptionHome: AuthScreen(route = "Option_Screen")
    object LogIn: AuthScreen(route = "LogIn_Screen")
    object Register: AuthScreen(route = "Register_Screen")
}

Это мой ДОМАШНИЙ ГРАФИК

      @SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainScreen(){
    val navController = rememberNavController()
    Scaffold(
        bottomBar = { BottomBar(navController = navController) }
    ) {
        BottomNavGraph(navController = navController)
    }
}

@Composable
fun BottomBar( navController: NavHostController) {
    val screens = listOf(
        BottomBarScreen.HomePage,
        BottomBarScreen.ProfilePage,
        BottomBarScreen.RankPage,
        BottomBarScreen.EcoPage,
        BottomBarScreen.StatisticsPage
    )
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentDestination = navBackStackEntry?.destination

    val bottomBarDestination = screens.any { it.route == currentDestination?.route }
    if (bottomBarDestination) {
        BottomNavigation {
            screens.forEach { screen ->
                AddItem(
                    screen = screen,
                    currentDestination = currentDestination,
                    navController = navController
                )
            }
        }
    }
}

@Composable
fun RowScope.AddItem(
    screen: BottomBarScreen,
    currentDestination: NavDestination?,
    navController: NavHostController
) {
    BottomNavigationItem(
        label = {
            Text(text = screen.title)
        },
        icon = {
            Icon(
                imageVector = screen.icon,
                contentDescription = "Navigation Icon"
            )
        },
        selected = currentDestination?.hierarchy?.any {
            it.route == screen.route
        } == true,
        unselectedContentColor = LocalContentColor.current.copy(alpha = ContentAlpha.disabled),
        onClick = {
            navController.navigate(screen.route) {
                popUpTo(navController.graph.findStartDestination().id)
                launchSingleTop = true
            }
        }
    )
}

Это моя страница входа, которая использует данные из API, который я создал.

      @Composable
fun LoginPage(
   onLoginClick: () -> Unit,

) {
    val coroutineScope = rememberCoroutineScope()

    val ctx = LocalContext.current

    remember{ mutableStateOf<List<UserN>?>(null) }

    val focusManager = LocalFocusManager.current

    val horizontalGradientBrush = horizontalGradient(
        colors = listOf(
            Color(0xff42FDD1),
            Color(0xff1BA803),
            Color(0xff38F477)
        )
    )
    val img1 = R.drawable.ic_visibility
    val img2 = R.drawable.ic_visibility_off
    val img3 = R.drawable.ic_password
    val img4 = R.drawable.ic_person


    var password by rememberSaveable { mutableStateOf("") }
    var passwordVisibility by remember { mutableStateOf(false) }
    var nameReg by remember { mutableStateOf("") }

    val icon = if (passwordVisibility) {
        painterResource(img1)
    } else {
        painterResource(img2)
    }
    //Logo Input
    Box(
        modifier = Modifier
            .fillMaxSize(),
        contentAlignment = Alignment.TopCenter
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black),
            contentAlignment = Alignment.Center
        ) {
            Image(
                modifier = Modifier
                    .size(280.dp)
                    .clip(CircleShape),
                painter = painterResource(id = R.drawable.logo3),
                contentDescription = "main-logo",
            )
        }
    }

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(15.dp, alignment = Alignment.Bottom),
        modifier = Modifier
            .navigationBarsPadding()
            .fillMaxSize()
            .fillMaxHeight(0.70f)
            .padding(24.dp)
        // .background(color = Color.Gray)
    )
    {
        Text(
            text = "Sign in",
            fontSize = 30.sp,
            fontStyle = FontStyle.Italic,
            fontWeight = FontWeight.Bold,
            color = Color.Green
        )
        OutlinedTextField(
            modifier = Modifier.border(
                width = 3.dp,
                brush = horizontalGradientBrush,
                shape = RoundedCornerShape(40.dp)
            ),
            value = nameReg,
            onValueChange = {
                nameReg = it
            },
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.Transparent,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                leadingIconColor = Color.Green,
                focusedLabelColor = Color.Green,
                unfocusedLabelColor = Color.Green,
                cursorColor = Color.Green,
                textColor = Color.Cyan
            ),
            placeholder = { Text(text = "Name") },
            label = { Text(text = "Enter your Name") },
            leadingIcon = {
                Icon(
                    painter = painterResource(img4),
                    contentDescription = "name register icon"
                )
            },
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Text,
                imeAction = ImeAction.Next
            ),
        )

        OutlinedTextField(
            modifier = Modifier.border(
                width = 3.dp,
                brush = horizontalGradientBrush,
                shape = RoundedCornerShape(40.dp)
            ),
            value = password,
            onValueChange = {
                password = it

            },
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.Transparent,
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                leadingIconColor = Color.Green,
                trailingIconColor = Color.Green,
                focusedLabelColor = Color.Green,
                unfocusedLabelColor = Color.Green,
                cursorColor = Color.Green,
                textColor = Color.Cyan
            ),
            placeholder = { Text(text = "Password") },
            label = { Text(text = "Enter your Password") },
            leadingIcon = {
                Icon(
                    painter = painterResource(img3),
                    contentDescription = "password icon"
                )
            },
            trailingIcon = {
                IconButton(onClick = {
                    passwordVisibility = !passwordVisibility
                }) {
                    Icon(
                        painter = icon,
                        contentDescription = "visibility icon"
                    )
                }
            },
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Password,
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(
                onDone = { focusManager.clearFocus() }
            ),
            visualTransformation = if (passwordVisibility) VisualTransformation.None
            else PasswordVisualTransformation()
        )
        Button(
            colors = ButtonDefaults.buttonColors(
                backgroundColor = Color.Green,
            ),
            onClick = {
                      onLoginClick()
                    coroutineScope.launch {
                        val aek = alpha(nameReg,password)
                        if (aek != "") {
                            onLoginClick()
                            
                        } else{
                            Toast.makeText(ctx, "Username or Password is wrong. Please try again!", Toast.LENGTH_SHORT).show()
                        }
                    }
            },
            border = BorderStroke(10.dp, color = Color.Green),
            shape = RoundedCornerShape(15.dp),
            modifier = Modifier
                .fillMaxWidth(0.43f)
                .fillMaxHeight(0.083f)
        )
        {
            Text(text = "Log in", color = Color.Black, fontSize = 18.sp)

        }
    }

}


suspend fun connection(): List<UserN> {
    val users = Utilities.getInstance().create(ApiInterface::class.java)

    return users.getItems()
}

suspend fun alpha(name: String, password: String): String {
    val person = connection()
    var correct = ""

    for (i in person.indices){
        if (name == person[i].userName && password == person[i].password) {
             correct = person[i].nickName
        }
    }
    return correct
}

Это мой BottomNavigationGraph

      @Composable
fun BottomNavGraph(
    navController: NavHostController
){

    NavHost(
        navController = navController,
        startDestination = BottomBarScreen.HomePage.route
    ){
        composable( route = BottomBarScreen.HomePage.route + "{aek}") {
            val item = it.arguments?.getString("aek")
            HomePage(count = item)
        }
        composable(route = BottomBarScreen.ProfilePage.route){
            ProfilePage()
        }
        composable(route = BottomBarScreen.RankPage.route){
            RankPage()
        }
        composable(route = BottomBarScreen.EcoPage.route){
            EcoPage()
        }
        composable(route = BottomBarScreen.StatisticsPage.route){
            StatPage()
        }
//        composable(route = BottomBarScreen.EvaluationPage.route){
//            EvalPage()
//        }
    }
}

Пожалуйста, помогите мне, я пытаюсь найти решение почти неделю.

0 ответов

Другие вопросы по тегам