Home > Software design >  GetX - Middleware don't watch state changes?
GetX - Middleware don't watch state changes?

Time:03-09

I want to build auth system, protected and unprotected routes.

Here is my code:

User modal:

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

Auth controller:

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;
  }
}

Auth middleware:

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;
  }
}

Login part:

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
     }
}

As a result, I have been all-time redirected to unprotected routes, because,

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

function in Auth controller returns false :)

Any suggestions?

CodePudding user response:

here

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

you are creating new instance of User instead of accessing current instance : user.value.isLogged

  • Related