0

我在 MainActivity 中有这个:

@Composable
fun createNavHost(paddingValues: PaddingValues, navController: NavHostController) {
    NavHost(navController, startDestination = Screen.HomeScreen.title) {
        composable(Screen.HomeScreen.title) {
            HomeScreen(
                accountSelected = {
                    navController.navigate(Screen.PasswordDetailScreen.title + "/${it.id}")
                })
        }
        composable(Screen.EditPasswordScreen.title) {
            EditPasswordScreen()
        }
    }
}

我的布局是这样定义的:

@Composable
fun MainLayout() {
    val navController = rememberNavController()

    PasswordHelperTheme {
        Scaffold(
        ) { paddingValues ->
            createNavHost(paddingValues, navController)
        }
    }
}

屏幕是这样定义的:

sealed class Screen(val title: String) {
    object HomeScreen : Screen("Home")
    object SettingsScreen : Screen("Settings")
    object EditPasswordScreen : Screen("Edit")
    object PasswordDetailScreen: Screen("ArticleDetail")
}

我打电话

@Composable fun AddAccountFAB() { val context = LocalContext val navController = rememberNavController()

ExtendedFloatingActionButton(
    shape = CircleShape,
    icon = { Icon(Icons.Filled.Add, "") },
    onClick = {
        navController.graph = navController.graph
        navController.navigate(MainActivity.Screen.EditPasswordScreen.title) {
            popUpTo = navController.graph.startDestination
            launchSingleTop = true
        }
    },
    elevation = FloatingActionButtonDefaults.elevation(8.dp),
    text = { Text("Add Account")}
)

并得到

java.lang.IllegalStateException: You must call setGraph() before calling getGraph()
        at androidx.navigation.NavController.getGraph(NavController.java:812)
        at com.blackfox.passwordhelper.android.HomeScreenKt$AddAccountFAB$1$1.invoke(HomeScreen.kt:79)

我以为createNavHost是在设置图表。这至少让我摆脱了深层链接异常。我只是想使用 FAB 转到一个页面。

4

2 回答 2

0

看来唯一真正的选择是routenavHost.

NavHost(navController, startDestination = Screen.HomeScreen.title) {
        composable(Screen.HomeScreen.title) {
            HomeScreen(
                accountSelected = {
                    navController.navigate(Screen.PasswordDetailScreen.title + "/${it.id}")
                },
                fabSelected = {
                    navController.navigate(Screen.EditPasswordScreen.title + "/${it.id}")
                })
        }
        composable(Screen.EditPasswordScreen.title + "/-1") {
            EditPasswordScreen()
        }
    }

这有效:

ExtendedFloatingActionButton(
    shape = CircleShape,
    icon = { Icon(Icons.Filled.Add, "") },
    onClick = {
        fabSelected(Passwords(-1, "", "", "", "", ""))
    },
    elevation = FloatingActionButtonDefaults.elevation(8.dp),
    text = { Text("Add Account")}
)
于 2021-05-22T19:40:43.653 回答
0

尝试删除

navController.graph = navController.graph
于 2021-05-17T06:27:06.123 回答