状态流导致喷气背包中的导航循环构成

发布于 2025-01-23 23:16:14 字数 679 浏览 0 评论 0原文

应用中有两个屏幕。屏幕A和屏幕B。屏幕A的UI和导航逻辑基于状态类。

筛选

data class ScreenAState(
    val sourceName: String = "",
    val navigateToScreenB: Boolean = false
)

如果用户满足要求,navigatetScreenb的值将更改为true,并且使用以下代码将用户导航到屏幕B。

if (uiState.navigateToScreenB) {
     LaunchedEffect(uiState.navigateToScreenB) {
          findNavController().navigate(actionToScreenB)
        }
    }

现在,当用户按下屏幕B上的后退按钮时,问题就会发生。一旦用户从屏幕B返回到屏幕A,用户再次导航到屏幕B,如果再次按下后退按钮,则循环继续屏幕B。

我不确定是否正确使用启动效果。任何帮助将不胜感激。谢谢。

There are two screens in the app. Screen A and Screen B. The UI and navigation logic of Screen A is based on the state class.

ScreenAState

data class ScreenAState(
    val sourceName: String = "",
    val navigateToScreenB: Boolean = false
)

If the user meets the requirements, the value of navigateToScreenB is changed to true and the user is navigated to Screen B using the following code.

if (uiState.navigateToScreenB) {
     LaunchedEffect(uiState.navigateToScreenB) {
          findNavController().navigate(actionToScreenB)
        }
    }

Now, the problem occurs when the user presses the back button on Screen B. As soon as the user comes back from Screen B to Screen A, the user is again navigated to Screen B and the loop continues if the back button is pressed again on Screen B.

I am not sure if I am using the LaunchedEffect properly. Any help will be appreciated. Thank You.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

粉红×色少女 2025-01-30 23:16:14

执行导航后,您应该将navigatetoscreenb设置为false。
在您的视图模型中声明这样的内容。

class YourViewModel: ViewModel() {
    private val _uiState = MutableStateFlow(ScreenAState())
    val uiState = _uiState.asStateFlow()

    fun onNavigateToScreenB() {
        uiState.update {
            it.copy(navigateToScreenB = false)
        }
    }
    ...
}    

在您的屏幕上:

val uiState by yourViewModel.uiState.collectAsState()
if (uiState.navigateToScreenB) {
    LaunchedEffect(uiState.navigateToScreenB) {
        viewModel.onNavigateToScreenB()
        findNavController().navigate(actionToScreenB)
    }
}

You should set navigateToScreenB to false after perform the navigation.
Declaring something like this in your view model.

class YourViewModel: ViewModel() {
    private val _uiState = MutableStateFlow(ScreenAState())
    val uiState = _uiState.asStateFlow()

    fun onNavigateToScreenB() {
        uiState.update {
            it.copy(navigateToScreenB = false)
        }
    }
    ...
}    

and in your screen:

val uiState by yourViewModel.uiState.collectAsState()
if (uiState.navigateToScreenB) {
    LaunchedEffect(uiState.navigateToScreenB) {
        viewModel.onNavigateToScreenB()
        findNavController().navigate(actionToScreenB)
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文