How do I implement a GoogleSignIn with Jetpack Compose?

Viewed 280

I'm trting to implement a GoogleSignIn with jetpack compose. I am able to start the GoogleSignIn but I get no result and it doesn't navigate to the next screen. How can I do it?

this is the code I'm trying:

const val RC_SIGN_IN = 123

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {

            val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build()

            val mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

val result = remember { mutableStateOf<Client?>(null)}
            val launcher = rememberLauncherForActivityResult(
                ActivityResultContracts.StartActivityForResult()){

                if (it.resultCode == RC_SIGN_IN) {
                    val task = GoogleSignIn.getSignedInAccountFromIntent(it.data)
                    try {
                        val account: GoogleSignInAccount? =
                           task.getResult(ApiException::class.java)
                        val client = Client(
                            account?.id!!,
                            account.displayName!!,
                            account.photoUrl!!.toString(),
                            account.email!!
                        )
                        Log.d("TAG", client.toString())
                        viewModel.addClient(client)
                        result.value = client
                        navController.navigate(Screen.HomeScreen.route)
                    } catch (e: ApiException) {
                        Toast.makeText(this, "login failed", Toast.LENGTH_LONG).show()
                    }
                }
            }

       Button(onClick = {launcher.launch(mGoogleSignInClient.signInIntent)})

1 Answers

You can do something like this

@Preview
@Composable
fun GoogleSignInButton(){
    Column {
        val signInBtn = SignInButton(LocalContext.current)
        AndroidView(factory = {signInBtn})
    }
}
Related