skip to Main Content

I have a StatusManger which has a timer to count down:

class StatusManager extends GetxController {
  factory StatusManager() => _getInstance();
  static StatusManager? _instance;

  Timer? _timer;
  var count = 60.obs;

  static _getInstance() {
    if (_instance == null) {
      _instance = StatusManager._();
    }
    return _instance;
  }

  StatusManager._() {}

  @override
  void onInit() {
    super.onInit();
    debugPrint('onInit');
  }

  @override
  void onClose() {
    debugPrint('onClose');
    super.onClose();
  }

  startTimer() {
    stopTimer();

    _timer = Timer.periodic(Duration(seconds: 1), (Timer t) {
      fetchStatus();
    });
  }

  stopTimer() {
    _timer?.cancel();
  }

  fetchStatus() async {
    count--;
  }
}

Now, in some widget, I wanna listen the remaining time and push to a new page.
I don’t use the count to build widget, I just listen the count value changed.

How can I to do this?

2

Answers


  1. You can achieve this functionality by using Getx Worker like this:

    class StatusManager extends GetxController {
      
      var count = 60.obs;
      Worker? listenerWorker;
      
      @override
      void onInit() async {
        super.onInit();
        listenerWorker = ever(count, (callback) {
          print("count: $callback ");
          // if(callback == 52){
          // add your logic or call related function here
          // }
        });
      }
      
      @override
      void onClose() async {
        listenerWorker?.dispose();
        super.onClose();
      }
      
    }
    
    Login or Signup to reply.
  2. you can try the below simple way that you can create a global variable to detect the time is end, for example:

    create a global variable class

    class Global {
       static RxBool isEndTime = false.obs;
    }
    

    and update this flag in your StatusManager

    startTimer() {
        stopTimer();
    
        _timer = Timer.periodic(Duration(seconds: 1), (Timer t) {
          fetchStatus();
        });
      }
    
      fetchStatus() async {
        count--;
        if(count == 0){
          Global.isEndTime.value = true;  //update to end time
        }
      }
    

    and check it in another widget

    if(Global.isEndTime.value) {
        Global.isEndTime.value = false; //reset the value
        Get.to(() => OtherPage());
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search