Flutter集成Google/YoutubeAPI+Firebase时authentication空指针等认证报错
问题排查与解决方案
1. 修复NoSuchMethodError: The getter 'authentication' was called on null错误
该错误的根本原因是googleSignIn.signInSilently()执行失败返回了null,你直接调用了null对象的authentication属性导致报错,修复方式如下:
- 对静默登录的返回结果做判空处理,如果返回null,主动触发交互式登录
- 给整个登录流程增加try-catch捕获异常
修改后的核心代码片段:
addPlayListItem(String videoID, String playlistID) async { final String apiUrl = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"; final FirebaseAuth _auth = FirebaseAuth.instance; final GoogleSignIn googleSignIn = GoogleSignIn( scopes: [ 'email', 'profile', 'https://www.googleapis.com/auth/youtube', ], ); GoogleSignInAccount? googleSignInAccount = await googleSignIn.signInSilently(); // 静默登录失败,主动触发登录 googleSignInAccount ??= await googleSignIn.signIn(); if (googleSignInAccount == null) { print("用户取消了登录,操作终止"); return; } final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication; // 后续原有逻辑保持不变 }
2. 修复iOS端403权限不足错误
错误提示Insufficient Permission对应以下几个排查点:
- 你之前登录过Google账号时没有申请YouTube的操作权限,本地缓存的token没有对应scope,需要先调用
googleSignIn.signOut()退出账号,重新登录获取新的带权限的token - 确认你的项目在Google Cloud控制台已经启用YouTube Data API v3
- 如果你的应用还在测试阶段,需要在Google Cloud控制台的「OAuth同意屏幕」页面,把测试用到的Google账号加入到测试用户列表中,否则敏感scope的授权会被拦截
3. 修复Android端12500登录错误
该错误是Google登录的通用错误,按以下顺序排查:
- 确认你在Firebase控制台配置的Android应用SHA-1签名正确,debug和release环境的签名都需要添加
- 确认你已经把Firebase控制台下载的最新
google-services.json文件,放到了项目的android/app/目录下 - 检查
android/app/src/main/AndroidManifest.xml中已经添加了网络权限:<uses-permission android:name="android.permission.INTERNET" /> - 确认Google Cloud控制台的「OAuth同意屏幕」已经完成基础配置,应用名称、开发者联系邮箱都已填写,没有未完成的配置项
- 测试阶段同样需要把测试账号加入到OAuth同意屏幕的测试用户列表中
内容的提问来源于stack exchange,提问作者JayProXter
相关产品推荐
相关产品推荐

