Jetpack Compose密码可见性切换问题:未认证即显示密码
问题分析
你的代码核心问题在于showBiometricPrompt是异步操作,但你在调用它之后立刻同步判断biometricResult——这时候生物认证流程还没走完,结果根本没更新,这段判断会直接用旧的biometricResult值执行,导致密码提前显示。
解决方案
要在生物认证完成后再更新密码可见状态,必须通过异步回调或协程等待认证结果返回后再处理状态。以下是修正后的代码:
// 1. 引入协程作用域 val coroutineScope = rememberCoroutineScope() var isAuthenticated by remember { mutableStateOf(false) } var show_pass by remember { mutableStateOf(false) } IconButton(onClick = { if (!isAuthenticated) { // 2. 启动协程处理异步认证 coroutineScope.launch { // 假设showBiometricPrompt是挂起函数,直接返回认证结果 val biometricResult = promptManager.showBiometricPrompt( title = "Authentication required", description = "Confirm it's you!" ) // 3. 认证完成后再更新状态 if (biometricResult is BiometricResult.AuthenticationSuccess) { isAuthenticated = true show_pass = true } else { isAuthenticated = false show_pass = false } } } else { // 已认证状态下点击,直接切换隐藏 isAuthenticated = false show_pass = false } }) { Icon( painter = painterResource(id = if (show_pass) R.drawable.eye_alt_svgrepo_com else R.drawable.eye_slash_alt_svgrepo_com), contentDescription = if (show_pass) "隐藏密码" else "显示密码", modifier = Modifier.size(24.dp) ) }
关键说明
- 用
rememberCoroutineScope在Compose中创建协程作用域,确保异步操作能正确更新Compose状态 - 把认证逻辑放到协程里,等待
showBiometricPrompt返回结果后再修改isAuthenticated和show_pass,这样就不会出现密码提前显示的问题 - 如果你的
showBiometricPrompt不是挂起函数,而是通过回调返回结果,那可以改为在回调里更新状态,比如:promptManager.showBiometricPrompt( title = "Authentication required", description = "Confirm it's you!", onResult = { result -> if (result is BiometricResult.AuthenticationSuccess) { isAuthenticated = true show_pass = true } else { isAuthenticated = false show_pass = false } } )
内容的提问来源于stack exchange,提问作者Ayush Thakur
相关产品推荐
相关产品推荐

