Search code examples
flutterlistener

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?


Solution

  • 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