gpt4 book ai didi

android - rememberLauncherForActivityResult 抛出 Launcher 尚未在 Jetpack Compose 中初始化

转载 作者:行者123 更新时间:2023-12-04 12:32:07 27 4
gpt4 key购买 nike

尝试调用 Firebase Auth UI 时,使用以下代码编译器会抛出 java.lang.IllegalStateException: Launcher has not been initialized。不确定,为什么启动器没有初始化

@Composable
internal fun ProfileUI(profileViewModel: ProfileViewModel) {
val loginLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result != null) {
//do something
}
}
if (profileViewModel.isAnonymousUser) {
loginLauncher.launch(profileViewModel.buildLoginIntent())

} else {


}
}

override fun buildLoginIntent(): Intent {

val authUILayout = AuthMethodPickerLayout.Builder(R.layout.auth_ui)
.setGoogleButtonId(R.id.btn_gmail)
.setEmailButtonId(R.id.btn_email)
.build()

return AuthUI.getInstance().createSignInIntentBuilder()
.setIsSmartLockEnabled(!BuildConfig.DEBUG)
.setAvailableProviders(
listOf(
AuthUI.IdpConfig.EmailBuilder().build(),
AuthUI.IdpConfig.GoogleBuilder().build()
)
)
.enableAnonymousUsersAutoUpgrade()
.setLogo(R.mipmap.ic_launcher)
.setAuthMethodPickerLayout(authUILayout)
.build()
}

java.lang.IllegalStateException: Launcher has not been initialized
at androidx.activity.compose.ActivityResultLauncherHolder.launch(ActivityResultRegistry.kt:153)
at androidx.activity.compose.ManagedActivityResultLauncher.launch(ActivityResultRegistry.kt:142)
at androidx.activity.result.ActivityResultLauncher.launch(ActivityResultLauncher.java:47)
at com.madhu.locationbuddy.profile.ProfileUIKt.ProfileUI(ProfileUI.kt:37)
at com.madhu.locationbuddy.profile.ProfileUIKt.ProfileUI(ProfileUI.kt:15)
关于如何解决这个问题的任何想法?

最佳答案

根据 Side-effects in Compose documentation :

Composables should be side-effect free.

Key Term: A side-effect is a change to the state of the app that happens outside the scope of a composable function.


启动另一个 Activity ,例如调用 launch , 绝对是一种副作用,因此永远不应该作为组合物本身的一部分。
相反,您应该在其中一个 Effect API 中调用 launch,例如 SideEffect (如果您希望它在每个组合上运行)或 LaunchedEffect (仅在输入更改时运行 - 如果 profileViewModel.isAnonymousUsermutableStateOf() 驱动,则适用)。
因此,您的代码可以更改为:
internal fun ProfileUI(profileViewModel: ProfileViewModel) {
val loginLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result != null) {
//do something
}
}
if (profileViewModel.isAnonymousUser) {
SideEffect {
loginLauncher.launch(profileViewModel.buildLoginIntent())
}
} else {
// Output your UI, etc.
}
}

关于android - rememberLauncherForActivityResult 抛出 Launcher 尚未在 Jetpack Compose 中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68331511/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com