android - 如果 auth 失败,如何显示 toast jetpack compose firebase if else @Composable 调用只能在 @Composable 函数的上下文中发生

标签 android kotlin android-jetpack-compose toast android-toast

<分区>

在 stackoverflow 上似乎有无数种解释此错误的方法,但没有一种能解决我的问题。

认证失败我想 toast

我正在使用 firebase 身份验证,但错误与位置上下文有关 enter image description here

如何突破这个限制?

按钮源代码

  Button(
                    onClick = {
                        auth.signInWithEmailAndPassword(email, password)
                            .addOnCompleteListener { task ->
                                if (task.isSuccessful) {
                                    navController.navigate(Screen.PreferenceScreen.route)
                                } else {
                                    // If sign in fails, display a message to the user.
                                    Log.w(TAG, "createUserWithEmail:failure", task.exception)
                                    Toast.makeText(
                                        LocalContext.current,
                                        "Authentication failed.",
                                        Toast.LENGTH_SHORT
                                    ).show()


                                }
                            }


                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(8.dp),
                    enabled = isPasswordValid && confirmPassword == password,
                ) {
                    Text(text = "Register")
                }   
}

最佳答案

只需在 Button 外部声明 context,然后像这样在 Toast 中使用它。

@Composable
fun MyButtonWithToast() {

    val context = LocalContext.current
  

    Button(
        onClick = {
            Toast.makeText(
                context,
                "Authentication failed.",
                Toast.LENGTH_SHORT
            ).show()
        }
    ) {
        Text(text = "Register")
    }
}

或者,如果您有一个可组合结构,只需在那里声明它并将其传递到此按钮所在的可组合结构中即可

@Composable
fun SomeParentComposable() {

    val context = LocalContext.current
    
    MyButtonWithToast(context = context)
}

关于android - 如果 auth 失败,如何显示 toast jetpack compose firebase if else @Composable 调用只能在 @Composable 函数的上下文中发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74677970/

相关文章:

android - slidingmenu/jfeinstein10项目如何通过触摸向后滑动左(或右)菜单?

android - 从 Firestore 获取数据,其中数组与 Kotlin 中的数据列表匹配

android - ClassNotFoundException : android. view.OnBackInvokedCallback with Compose 1.2.0-alpha07

php - SQL INSERT 语句在不应该执行的时候执行

android - 在撰写中自动滚动多行文本字段

Kotlin - 动态实例化所有内部类

android - 测试 Android Compose State 值

android - 如何使 BasicTextField 上的光标以 jetpack compose 为中心?

android - java.lang.UnsatisfiedLinkError when loading native library in Android 5.0

android - 如何在 BottomNavigationView 的 menuItem 上隐藏工具提示?