Home > Back-end >  Flutter - How to retrieve an implemented class with Get.find after registered with Get.put using Get
Flutter - How to retrieve an implemented class with Get.find after registered with Get.put using Get

Time:02-15

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())"

CodePudding user response:

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

}

CodePudding user response:

GetX finds its dependencies based on its exact types so you need to use Get.find<GetConnectApiHelper>()

updated:

class SignInBinding extends Bindings {

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

}

class SignInController<T extends IApiHelper> extends GetxController {

  final IApiHelper apiHelper = Get.find<T>(); 

}
  • Related