Flutter中使用sign_in_with_apple:^4.3.0实现Apple ID登录报错如何解决?
解决sign_in_with_apple ^4.3.0 登录Firebase的错误
核心错误修正点
- 移除不必要的转码操作:4.3.0版本中,
credential.authorizationCode和credential.identityToken本身就是String类型,无需使用String.fromCharCodes转换。 - 使用Firebase官方推荐的Provider实例:替换
OAuthProvider("apple.com")为OAuthProvider.appleProvider(),避免类型不匹配问题。 - 手动处理用户全名:Apple仅在用户首次登录时返回全名,需手动更新Firebase用户的
displayName,否则该字段会为空。
修正后的完整代码
Future<void> signInWithApple() async { try { final credential = await SignInWithApple.getAppleIDCredential( scopes: [ AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName, ], ); // 使用官方Apple Provider实例 final appleAuthProvider = OAuthProvider.appleProvider(); // 直接使用authorizationCode和identityToken final AuthCredential authCredential = appleAuthProvider.credential( accessToken: credential.authorizationCode, idToken: credential.identityToken, ); // 登录Firebase final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(authCredential); // 手动更新用户全名(仅首次登录有效) final user = userCredential.user; if (user != null && credential.fullName != null) { final displayName = "${credential.fullName?.givenName} ${credential.fullName?.familyName}"; await user.updateDisplayName(displayName); await user.reload(); // 重新加载用户信息获取更新后的displayName } // 更新本地状态 _email = user?.email; _uid = user?.uid; _displayName = user?.displayName; notifyListeners(); } catch (e) { print(e); _hasError = true; _errorCode = e.toString(); notifyListeners(); } }
额外注意事项
- 确保iOS端配置正确:在
Runner/Info.plist中添加Apple登录权限和回调URL,同时在Apple Developer后台配置好服务ID与重定向URI。 - 测试需使用真实iOS设备或iOS模拟器(macOS模拟器可能无法正常触发Apple登录流程)。
- 检查Firebase控制台是否已启用Apple登录方式,且配置的服务ID与Apple后台完全一致。
内容的提问来源于stack exchange,提问作者Dasun Dola
相关产品推荐
相关产品推荐

