0

I am trying to run a timer function and when the timer value reached a particular value i need to trigger another function. so i need to listen to the value change in the int start


import 'dart:async';


class CustomTimer{

  Timer _timer;
  int start = 0;


  void  startTimer(){
    const oneSec = Duration(seconds: 1);

    _timer = Timer.periodic(oneSec, (Timer timer){
      start++;
      print('start value $start');
    });
  }

  void cancelTimer()
  {
    _timer.cancel();
  }

}

I am calling this function from another class, How can i do that?

Alvin John Babu
  • 1,710
  • 2
  • 16
  • 26
  • Does this answer your question? [Listening to a variable change in flutter](https://stackoverflow.com/questions/56421959/listening-to-a-variable-change-in-flutter) – Paul Mar 04 '22 at 09:15

2 Answers2

4

You should be implement below way

class CustomTimer {

  Timer _timer;
  int start = 0;
  StreamController streamController;

  void startTimer() {
    const oneSec = Duration(seconds: 1);
    streamController = new StreamController<int>();
    _timer = Timer.periodic(oneSec, (Timer timer) {
      start++;
      streamController.sink.add(start);
      print('start value $start');
    });
  }

  void cancelTimer() {
    streamController.close();
    _timer.cancel();
  }

}

Other class when you listen updated value

class _EditEventState extends State<EditEvent> {

  CustomTimer customTimer = new CustomTimer();



  @override
  void initState() {
    customTimer.startTimer();
    customTimer.streamController.stream.listen((data) {
      print("listen value- $data");
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container()

    );
  }


 @override
  void dispose() {
    customTimer.cancelTimer();
    super.dispose();
  }
}

Here, I have created on streambuilder for listen int value

Nikhil Vadoliya
  • 1,542
  • 10
  • 17
1

int doesn't have something like a listener. But you could check for your event inside your regulary called timer function and then run a submitted method:

import 'dart:async';

class CustomTimer{

  Timer _timer;
  int start = 0;
  Function callback;

  void  startTimer(Function callback, int triggerValue){
    const oneSec = Duration(seconds: 1);

    _timer = Timer.periodic(oneSec, (Timer timer){
      start++;
      print('start value $start');

      if (start >= triggerValue)
        callback();
    });
  }

  void cancelTimer()
  {
    _timer.cancel();
  }

}

You can call it with this:

CustomTimer timer = CustomTimer();
timer.startTimer(10, () {
  print('timer has reached the submitted value');
  timer.cancelTimer();
});
josxha
  • 1,110
  • 8
  • 23