简体   繁体   中英

Flutter: how to listen to a int change?

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM