'Define Extension function on GETx

I am trying to define an extension function on GetInterface as

extension FindOrPut on GetInterface {
  S findOrPut<S>(S dependency,{String? tag}){
    if(GetInstance().isRegistered<S>(tag: tag)){
      return GetInstance().find<S>(tag: tag);
    }
    return GetInstance().put<S>(dependency,tag: tag);
  }
}

Which is same as the extension Inst on GetInterface developed by the GETx team. But my code is not working as expected.

Note: If I put the extension function code in the same file where it will be used; It works fine. But if I put the above code in the separate file function not found on Get.



Solution 1:[1]

I created the FindOrPut extension on GetInterface. Please check the below code it is working fine.

import 'package:amigo/src/controllers/test_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

extension FindOrPut on GetInterface {
  S findOrPut<S>(
    S dependency, {
    String? tag,
    bool permanent = false,
    InstanceBuilderCallback<S>? builder,
  }) {
    if (GetInstance().isRegistered<S>(tag: tag)) {
      return GetInstance().find<S>(tag: tag);
    }
    return GetInstance().put<S>(dependency, tag: tag, permanent: permanent);
  }
}

class ExtensionTesting extends StatelessWidget {
  ExtensionTesting({Key? key}) : super(key: key);

  //TODO: Include your getx controller here with findOrPut function
  final TestController _testController = Get.findOrPut(TestController());

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white30,
      child: Obx(() => Text(_testController.name.value)),
    );
  }
}

For working code please check the extension_method_implementation repo.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1