3

There appear to be an infinite number of explanations for this error on stackoverflow, none of which address my issue.

I want to show a toast if the authentication failed

I am using firebase auth but the error is with the Location context enter image description here

how can I pass through this limitation?

source code for the button

  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")
                }   
}
z.g.y
  • 5,512
  • 4
  • 10
  • 36
Dolev Dublon
  • 643
  • 1
  • 6
  • 16

1 Answers1

1

Just declare the context outside of the Button, and use it in the Toast like this.

@Composable
fun MyButtonWithToast() {

    val context = LocalContext.current
  

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

or if you have a composable structure, just simply declare it there and pass it in the composable this button is in

@Composable
fun SomeParentComposable() {

    val context = LocalContext.current
    
    MyButtonWithToast(context = context)
}
z.g.y
  • 5,512
  • 4
  • 10
  • 36
  • 1
    thank you i just didnt found the correct Composable invocations can only happen from the context of a Composable function post on stack overflow lol – Dolev Dublon Dec 04 '22 at 15:49