报错: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(); }
补充说明
auth.currentUser是同步属性,直接返回当前已登录的用户实例,无需异步等待- 增加空值判断是为了避免本地SharedPreferences标记已登录,但实际用户会话失效的情况,增强代码健壮性
内容的提问来源于stack exchange,提问作者Praveesh Ramroop
相关产品推荐
相关产品推荐

