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

报错:currentUser非函数无法调用,求身份验证代码修改方案

Flutter认证初始化报错修复思路

报错原因

报错The expression doesn't evaluate to a function, so it can't be invoked(对应currentUser),是因为你调用的auth.currentUser()是错误用法——当前Firebase Auth的currentUser是属性而非方法,不能加括号()当作函数调用。

修改方案

直接将auth.currentUser()改为auth.currentUser,同时简化异步逻辑(因为currentUser是同步属性,无需await和then):

修改后的完整代码

_initialize() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool loggedIn = prefs.getBool(LOGGED_IN) ?? false;
  if (!loggedIn) {
    _status = Status.Unauthenticated;
  } else {
    final currentUser = auth.currentUser;
    if (currentUser != null) { // 增加空值判断,避免后续uid为空报错
      _user = currentUser;
      _status = Status.Authenticated;
      _userModel = await _userServices.getUserById(currentUser.uid);
    } else {
      // 处理本地标记已登录但实际无用户的情况,重置状态
      _status = Status.Unauthenticated;
      await prefs.setBool(LOGGED_IN, false);
    }
  }
  notifyListeners();
}

补充说明

  1. auth.currentUser是同步属性,直接返回当前已登录的用户实例,无需异步等待
  2. 增加空值判断是为了避免本地SharedPreferences标记已登录,但实际用户会话失效的情况,增强代码健壮性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:30:58