Home > Net >  How can I stop Timer period in Flutter?
How can I stop Timer period in Flutter?

Time:11-15

class _LiftButtonLayerState extends State<LiftButtonLayer> {
  late Timer _timer;
  late double _timeElapsed;
  var isPause = false;
  var isTrue = true;

  @override
  void initState() {
    super.initState();
  }

  repeatDownActivate() {
    _timeElapsed = 0;
    final timer = Timer.periodic(Duration(milliseconds: 200), (timer) {
      liftDownButton.postReq();
      print("down singal 5per 1 second  ");
    });
  }
Container(
              width: 180,
              height: 60,
              child: GFButton(
                onPressed: () {
                  repeatUpActivate();
                  print('clicked Up Button');
                },
                text: '▲',
                textStyle: const TextStyle(
                  fontSize: 26,
                  color: GFColors.WHITE,
                ),
                shape: GFButtonShape.pills,
                size: GFSize.LARGE,
                buttonBoxShadow: true,
              )),

I found out that I can use Timer.cancel() from Flutter's Timer library.

I made a function for timer.cancel() , and applied timer.cancel() to onPressed on the new other button, but it doesn't work.

repeatUpActivate(isTrue) {
  if (isTrue == '200') {
    _timeElapsed = 0;
    var _timer = Timer.periodic(Duration(milliseconds: 200), (timer) {
      liftUpButton.postReq();
      print("down singal 5per 1 second  (ms)");
    });
  } else {
    return false;
  }
}
child: GFButton(
  onPressed: () {
    repeatUpActivate('900');
  },

CodePudding user response:

can this help you? to better understand how to cancel a timer

late Timer _timer;
  int i = 0;
  
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    launchTimer();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Test")),
      body: Center(
        child: ElevatedButton(
          child: Text('stop timer'),
          onPressed: () async {
            stopTimer(stopTimer: true);
          },
        ),
      ),
    );
  }

  void launchTimer() {
    _timer = Timer.periodic(Duration(milliseconds: 200), (timer) {
      i  ;
      print(i);
    });
  }

  void stopTimer({required bool stopTimer}) {
    if (stopTimer) {
      _timer.cancel();
    }
  }
  • Related