Search code examples
flutterdartflutter-getx

Flutter - How to retrieve an implemented class with Get.find after registered with Get.put using GetX?


I have a class called GetConnectApiHelper that implemented an abstraction called IApiHelper, I need to register this class with Get.put inside Bindings and retrieve the implementation inside an abstraction variable but when I try to do that I get an error about "the abstraction is not registered".

How can I inject the dependency correctly making it easy to change in case I need to replace with http, dio etc...(clean architecture)

abstract class IApiHelper {}

class GetConnectApiHelper extends GetxService implements IApiHelper {}

class SignInBinding extends Bindings {

  @override
  void dependencies() {
    Get.put(GetConnectApiHelper());
    Get.put(SignInController());
  }

}

class SignInController extends GetxController {

  final IApiHelper apiHelper = Get.find(); // This throws the exception

}

======== Exception caught by widgets library =======================================================
The following message was thrown building Builder(dirty):
"IApiHelper" not found. You need to call "Get.put(IApiHelper())" or "Get.lazyPut(()=>IApiHelper())"

Solution

  • I found a solution. I can set the Interface as a Type and then register the implementation I want to be retrieved.

    class SignInBinding extends Bindings {
    
      @override
      void dependencies() {
        Get.put<IApiHelper>(GetConnectApiHelper());
        Get.put(SignInController());
      }
    
    }
    
    class SignInController extends GetxController {
    
        final IApiHelper apiHelper = Get.find();
    
    }
    
    print(apiHelper.runtimeType); // it prints Instance of 'GetConnectApiHelper'
    

    Or I can inject the implementation.

    class SignInBinding extends Bindings {
    
      @override
      void dependencies() {
        Get.put<IApiHelper>(GetConnectApiHelper());
        Get.put(SignInController(apiHelper: Get.find()));
      }
    
    }
    
    class SignInController extends GetxController {
    
        final IApiHelper apiHelper;
        SignInController({required this.apiHelper})
    
    }