Flutter中Firebase signInWithCredential社交登录返回phoneNumber为null问题
Firebase社交登录(Google/Facebook/Apple)phoneNumber字段始终为null的解决方案
问题重现
Firebase返回的用户信息示例:
{"additionalUserInfo": {"isNewUser": true,"user": {"displayName":"i set it private","email":"i set it private","phoneNumber":null,"photoURL":"i set it private"}}
测试用Google登录代码:
void googleSingIn() async { emit(GoogleAuthLoadingState()); if (await checkConnectivity() == AppConstants.connectivityWifi || await checkConnectivity() == AppConstants.connectivitymobile) { try { // Trigger the authentication flow final GoogleSignIn googleSignIn = GoogleSignIn(); final GoogleSignInAccount? googleSignInAccount = await googleSignIn.signIn(); if (googleSignInAccount == null) { return; } // Obtain the auth details from the request final GoogleSignInAuthentication googleAuth = await googleSignInAccount.authentication; // Create a new credential final credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken); // Once signed in, return the UserCredential final userCredential = await FirebaseAuth.instance.signInWithCredential(credential); final googleUser = userCredential.user; final additionalUserInfo = userCredential.additionalUserInfo; dev.log("$userCredential"); if (additionalUserInfo!.isNewUser == false) { login( email: googleUser!.email!, password: googleUser.uid, method: AppConstants.googleMethod, ); } else { RouteGenerator.registerCubit.register( google: googleUser!.email, googlePassword: googleUser.uid, firstName: additionalUserInfo.profile?["given_name"], lastName: additionalUserInfo.profile?["family_name"], image: googleUser.photoURL, ); } } catch (e) { emit(GoogleAuthErrorState(error: e.toString())); } } else { emit(LogInConnectivity( connectivityMessage: StringsManager.connectionError)); } }
核心原因
Google、Facebook、Apple等平台默认不会将用户手机号共享给第三方应用,Firebase无法直接从登录凭证中获取该字段,必须主动请求对应权限并通过平台特定API获取。
分平台解决方案
Google登录
请求手机号权限
修改GoogleSignIn初始化代码,添加手机号相关scope:final GoogleSignIn googleSignIn = GoogleSignIn( scopes: [ 'email', 'profile', 'https://www.googleapis.com/auth/userinfo.phone' // 添加该scope请求手机号权限 ], );通过People API获取手机号
先在Google Cloud控制台启用People API,再用登录返回的accessToken调用API:// 获取googleAuth后执行 final http.Response response = await http.get( Uri.parse('https://people.googleapis.com/v1/people/me?personFields=phoneNumbers'), headers: {'Authorization': 'Bearer ${googleAuth.accessToken}'}, ); if (response.statusCode == 200) { final data = jsonDecode(response.body); final phoneNumbers = data['phoneNumbers'] as List?; if (phoneNumbers != null && phoneNumbers.isNotEmpty) { final phoneNumber = phoneNumbers[0]['value']; // 可选择将手机号存入自有数据库,或通过Firebase的updatePhoneNumber方法更新用户字段(需完成手机号验证流程) } }注意:用户可能未绑定手机号或拒绝授权,需处理空值情况。
Facebook登录
后台配置权限
在Facebook开发者后台,为应用添加public_profile、email、user_phone_number权限。登录时请求权限
final LoginResult result = await FacebookAuth.instance.login( permissions: ['public_profile', 'email', 'user_phone_number'], );提取手机号
final userData = await FacebookAuth.instance.getUserData( fields: 'name,email,phone', ); final phoneNumber = userData['phone']; // 后续处理同Google登录注意:
user_phone_number权限需通过Facebook应用审核后,才能面向非测试用户开放。
Apple登录
Apple登录仅在首次登录且用户同意共享手机号时,可通过凭证解析获取手机号,后续登录无法再获取,需自行存储:
final credential = await SignInWithApple.getAppleIDCredential( scopes: [ AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName, ], );
需通过后端服务调用Apple官方验证接口,解析credential.authorizationCode或identityToken提取手机号,前端无法直接解析。
通用注意事项
- Firebase Auth的
user.phoneNumber字段仅在手机号验证码登录,或主动调用updatePhoneNumber并完成验证后才会被设置,社交登录不会自动填充。 - 所有平台的手机号权限需符合平台政策,部分权限需提交审核才能全面开放。
- 必须处理用户拒绝授权或未绑定手机号的情况,避免空值引发崩溃。
内容的提问来源于stack exchange,提问作者Ahmed Hussein
相关产品推荐
相关产品推荐

