0
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');
  },
pmatatias
  • 3,491
  • 3
  • 10
  • 30
  • where are you cancelling the timer? Also, _timer is not assigned anywhere. – Rahul Nov 15 '22 at 05:49
  • 2
    Your `var _timer = Timer.periodic(...)` line assigns the `Timer` object to a *local* variable, not to `_LiftButtonLayerState`'s `_timer` member variable. Additionally, the `isTrue == '200'` check seems quite unlikely to ever be true, and I don't see any code that prevents you from creating additional periodic `Timer`s when one is already active. – jamesdlin Nov 15 '22 at 06:38

1 Answers1

0

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();
    }
  }
Fugipe
  • 386
  • 1
  • 8