Search code examples
flutterflutter-getx

How to listen changes inside TextController?


I am using GetX. I need to listen changes in TextController. The follow code do not work:

class Controller extends GetxController{

  final txtList = TextEditingController().obs;

  @override
  void onInit() {
    debounce(txtList, (_) { 
      print("debouce$_");
      }, time: Duration(seconds: 1));
    super.onInit();
  }

}

Is does not print nothing when I am changing txtList value from UI. I suppose it's because it does not check text field inside txtList.

How to get it work?


Solution

  • You need to pass an RxInterface into debounce to do this via GetX. Just create an RxString and add a listener to the controller then pass the RxString into debounce.

    class Controller extends GetxController {
      final txtList = TextEditingController();
    
      RxString controllerText = ''.obs;
    
      @override
      void onInit() {
        txtList.addListener(() {
          controllerText.value = txtList.text;
        });
        
        debounce(controllerText, (_) {
          print("debouce$_");
        }, time: Duration(seconds: 1));
        super.onInit();
      }
    }
    

    Then on any page in the app you can pass in that controller into the textfield and it'll print the value after the user stops typing for 1 second.

    class Home extends StatelessWidget {
     final controller = Get.put(Controller());
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: TextField(controller: controller.txtList), // this will print
          ),
        );
      }
    }
    

    And if you need that value for anything else it's also always accessible via controller.controllerText.value.