繁体   English   中英

Android 撰写小吃栏在配置更改时再次显示

[英]Android compose snackbar showing again on config changes

我想在android compose上显示一次snackbar,但是一旦我改变了屏幕旋转,snackbar就会再次显示,我从官方android文档中获取了这个例子,它正在做同样的事情:

@Composable
fun LoginScreen(
    state: Boolean = true,
    scaffoldState: ScaffoldState = rememberScaffoldState()
) {
    // If the UI state contains an error, show snackbar
    if (state) {

        // `LaunchedEffect` will cancel and re-launch if
        // `scaffoldState.snackbarHostState` changes
        LaunchedEffect(scaffoldState.snackbarHostState) {
            // Show snackbar using a coroutine, when the coroutine is cancelled the
            // snackbar will automatically dismiss. This coroutine will cancel whenever
            // `state.hasError` is false, and only start when `state.hasError` is true
            // (due to the above if-check), or if `scaffoldState.snackbarHostState` changes.
            scaffoldState.snackbarHostState.showSnackbar(
                message = "Error message",
                actionLabel = "Retry message"
            )
        }
    }

    Scaffold(scaffoldState = scaffoldState) {
    }
}

我的问题是:即使旋转发生变化,您如何显示一次带有副作用的小吃店?

例如,您可以使用rememberSaveable将状态保存到局部变量,并在小吃店消失时将其设置为false

var localState by rememberSaveable(state) { mutableStateOf(state) }
// If the UI state contains an error, show snackbar
if (localState) {

    // `LaunchedEffect` will cancel and re-launch if
    // `scaffoldState.snackbarHostState` changes
    LaunchedEffect(scaffoldState.snackbarHostState) {
        // Show snackbar using a coroutine, when the coroutine is cancelled the
        // snackbar will automatically dismiss. This coroutine will cancel whenever
        // `state.hasError` is false, and only start when `state.hasError` is true
        // (due to the above if-check), or if `scaffoldState.snackbarHostState` changes.
        scaffoldState.snackbarHostState.showSnackbar(
            message = "Error message",
            actionLabel = "Retry message"
        )
        localState = false
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM