Context: I have a signup form with Google signin option.
Problem: If invoke signIn() inside onPressed listener, it works. But if I perform the invocation inside my CustomerRegistrationBloc, it throws:
PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null)
// Google SignIn Button
class _GoogleSigninButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<CustomerRegistrationBloc, CustomerRegistrationState>(
buildWhen: (previous, current) => previous.status != current.status,
builder: (context, state) {
return ElevatedButton(
onPressed: () async {
try {
// !!! This can work!
// GoogleSignIn _googleSigin = GoogleSignIn();
// await _googleSigin.signOut();
// var user = await _googleSigin.signIn();
// !!! This cannot work!
context
.read<CustomerRegistrationBloc>()
.add(GoogleSignUpSelected());
} catch (ex) {
print(ex);
}
},
key: const Key('customerRegistrationForm_google_signUpButton'),
child: Icon(Icons.menu, color: Colors.white),
style: ElevatedButton.styleFrom(
shape: CircleBorder(),
padding: EdgeInsets.all(14),
primary: Colors.blue,
onPrimary: Colors.red,
),
);
},
);
}
}
class CustomerRegistrationBloc
extends Bloc<CustomerRegistrationEvent, CustomerRegistrationState> {
CustomerRegistrationBloc(): super(CustomerRegistrationState());
@override
Stream<CustomerRegistrationState> mapEventToState(
CustomerRegistrationEvent event,
) async* {
if (event is GoogleSignUpSelected) {
yield* _handleSignUpWithGoogle(event, state);
}
}
Stream<CustomerRegistrationState> _handleSignUpWithGoogle(
GoogleSignUpSelected event, CustomerRegistrationState state) async* {
try {
yield state.copyWith(status: FormzStatus.submissionInProgress);
// sign in with google
GoogleSignIn _googleSigIn = GoogleSignIn();
var account = await _googleSigIn.signIn();
if (account != null) {
// get user info and populate to state
yield state.copyWith(status: FormzStatus.submissionSuccess);
}
} catch (ex) {
print(ex);
yield state.copyWith(status: FormzStatus.submissionFailure);
}
}
}