You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Firebase邮箱密码登录成功但Credentials返回Null

问题原因

邮箱密码登录方式下,signInWithEmailAndPassword返回的UserCredential.credential字段本身就是null——这个字段仅针对第三方OAuth登录(如Google、Apple登录)才会填充凭证数据,属于Firebase Auth的正常设计,并非异常或集成错误。

解决方案

要获取用户的访问令牌,需从UserCredential.user对象中获取idToken(JWT格式,用于后端身份验证),具体实现如下:

  1. 登录成功后,从userCredential中取出用户实例
  2. 调用getIdToken()方法获取最新的idToken(该方法会自动刷新过期令牌)

修改后的代码示例:

try {
  setState(() => isLoading = true);
  final userCredential = await FirebaseAuth
      .instance
      .signInWithEmailAndPassword(
          email: email!, password: password!);
  
  // 获取用户idToken(即所需的accessToken)
  final idToken = await userCredential.user?.getIdToken();
  print('idToken: $idToken');

  if (mounted) {
    Provider.of<UserCredentialsProvider>(
            context,
            listen: false)
        .setUser(userCredential);
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const Home(),
      ),
    );
  }
} on FirebaseAuthException catch (e) {
  if (e.code == 'user-not-found') {
    SimpleUtilities().errorSnackBar(context,
        snackbarData:
            'No user linked with this email.');
  } else if (e.code == 'wrong-password') {
    SimpleUtilities().errorSnackBar(context,
        snackbarData:
            'Wrong password provided.');
  }
} catch (e) {
  SimpleUtilities().errorSnackBar(context,
      snackbarData: e.toString());
}
补充说明
  • idToken是短期有效的JWT令牌,默认有效期1小时,调用getIdToken()时若令牌已过期,Firebase会自动刷新并返回新令牌
  • 若需长期维持登录状态,可使用user.refreshToken获取刷新令牌,用于后续主动刷新idToken
  • 控制台日志中Notifying id token listeners about user的提示,已说明用户登录流程完全正常

内容的提问来源于stack exchange,提问作者siffat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 22:17:20