【问题标题】:how to show toast if auth failed jetpack compose firebase if else @Composable invocations can only happen from the context of a @Composable function [duplicate]如果 auth 失败,如何显示吐司 jetpack compose firebase if else @Composable 调用只能在 @Composable 函数的上下文中发生 [重复]
【发布时间】:2022-12-05 00:02:58
【问题描述】:

关于 stackoverflow 上的这个错误似乎有无数种解释,但没有一个能解决我的问题。

如果身份验证失败,我想举杯祝酒

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

我怎样才能通过这个限制?

按钮的源代码

  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")
                }   
}

【问题讨论】:

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


    【解决方案1】:

    只需在 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)
    }
    

    【讨论】:

    • 谢谢,我只是没有找到正确的可组合调用只能在可组合函数的上下文中发生在堆栈溢出上 lol
    • 解决业务再多 50 分,你就在 6000
    猜你喜欢
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多