GetX - 中间件不观察状态变化?

GetX - Middleware don't watch state changes?

我想建立认证系统,受保护和不受保护的路由。

这是我的代码:

用户模式:

class User {
  User({this.username = '', this.isLogged = false, this.loginCookie = ''});
  String username;
  String loginCookie;
  bool isLogged;
}

授权控制器:

class UserController extends GetxController {
  final user = User().obs;

  loginUser(Object userData) {
    user.update((val) {
      val?.isLogged = true;
    });
  }

  logOutUser() {
    user.update((val) {
      val?.username = '';
      val?.isLogged = false;
      val?.loginCookie = '';
    });
  }

  isUserLogged() {
    return User().isLogged;
  }
}

授权中间件:

class AuthMiddleware extends GetMiddleware {
  @override
  int? get priority => 1;
  bool isAuthenticated = false;

  final authService = Get.find<UserController>().isUserLogged; //Here comes true/false

  @override
  RouteSettings? redirect(String? route) {
    isAuthenticated = authService();
    if (isAuthenticated == false) {
      return const RouteSettings(name: '/login');
    }
    return null;
  }
}

登录部分:

onPressed() async {
     final isLogged = Get.find<UserController>().loginUser; //With this function I want to update state in state controller, function loginUser();
     await AuthService().loginUser(email,password).then((res) => { 
        isLogged(response), //Runs loginUser();
        Get.toNamed('/home') //Home is protected by Auth middleware above
     }
}

因此,我一直被重定向到不受保护的路由,因为,

isUserLogged() {
    return User().isLogged;
  }

Auth 控制器中的函数 returns false :)

有什么建议吗?

这里

isUserLogged() {
  return User().isLogged;
}

您正在创建 User 的新实例而不是访问当前实例:user.value.isLogged