Ali Alqallaf
Ali Alqallaf

Reputation: 1007

Can I use getx controller inside another getx controller?

I am using Get (getx) package to manage the state of my app, and I am trying to use a controller inside another one. For example I have a class the contains methods for firebase authentication

class FirebaseAuthController extends GetxController {

  static FirebaseAuthController get to => Get.find<FirebaseAuthController>();
  .....

  Future<void> createUser(String email, String password) async {
    try {
      await _auth.createUserWithEmailAndPassword(
          email: email, password: password);
    } catch (e) {
      ...
    }
  }

...
...
}

and I have another controller which is signUpController that interacts with the UI


class SignInController extends GetxController {
  static SignInController get to => Get.find<SignInController>();

...
....

  Future<void> clickSignInButton() async {
    print(emailController.text);
    print(passwordController.text);
    if (formKey.currentState.validate()) {
      try {
        await FirebaseAuthController.to
             .login(emailController.text, passwordController.text);
      } catch (e) {
        print(e);
      }
    }
  }
}

when I try to do this, it gives me an error

lib/screens/authentication_screens/controller/sign_up_controller.dart:56:37: Error: Getter not found: 'to'.
       await FirebaseAuthController.to

any idea what might be the issue?

Upvotes: 3

Views: 3675

Answers (2)

Muhammad Sheraz
Muhammad Sheraz

Reputation: 191

yes you can use one controller in another controller and user its variable and also update it

Example

class HomeController extends GetxController {
    var home = '';
    String userName = '';
    updateName() {}
}

class LoginController extends GetxController {
    HomeController homeController = Get.put(HomeController());
    String email = '';
    String password = '';

    signin() {
        email = homeController.userName;
        homeController.updateName();
        homeController.update();
    }
}

Upvotes: 2

S. M. JAHANGIR
S. M. JAHANGIR

Reputation: 5020

You absolutely can, despite it's considered a bad practice. It's recommended to use something like repository or usecase classes instead unless you want to update the data shown on the screen attached to that controller from another controller.

And for the solution to your actual problem or error, just change static FirebaseAuthController get to => Get.find<FirebaseAuthController>(); to static FirebaseAuthController get to => Get.put(FirebaseAuthController());

Upvotes: 1

Related Questions