首页 > 解决方案 > 使用 Flutter BLoc 登录 Google 失败

问题描述

上下文:我有一个带有 Google 登录选项的注册表单。

问题:如果在侦听器signIn()内部调用,它可以工作。onPressed但是如果我在 my 中执行调用CustomerRegistrationBloc,它会抛出:

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

标签: flutterdartgoogle-signinflutter-bloc

解决方案


推荐阅读