Stop Timer periodic on other dateTime/NTPTime Flutter

I have 2 function that call NTP to get local date time. First one is working like a clock using Timer.periodic and the second one for get the time when user tapped the button. But when I display the time in the second function its still runing the Timer.periodic. How to avoid that? Thanks

My Code:

Future<String> getNTPTime() async {
DateTime startDate = await NTP.now();
String currentDate = DateFormat('d MMMM yyyy').format(startDate);
String currentTime = DateFormat('kk : mm : ss').format(startDate);
print('NTP DateTime: $startDate');

if (mounted) {
  setState(() {
    _currentDate = currentDate;
    _currentTime = currentTime;
  });
}}

Future<String> getNTPTimeIn() async {
DateTime ntpTimeIn = await NTP.now();

String timeIn = DateFormat('kk : mm : ss').format(ntpTimeIn);
print('NTP DateTime: $ntpTimeIn');


if (mounted) {
  setState(() {
    _ntpTimeIn = timeIn;
  });
}}

and call it in the initState

@override
super.initState();
getNTPTime();
Timer.periodic(Duration(seconds: 1), (timer) => getNTPTime());
}

when I display the _ntpTimeIn the Timer.periodic is still running.

1 answer

  • answered 2021-07-30 15:03 Constantin N.

    This is how you should implement it.

    class YourClas extends StatefulWidget{
    Timer _timer;
    
    @override
    void initState(){
    super.initState();
    getNTPTime();
    _timer = Timer.periodic(Duration(seconds: 1), (timer) => getNTPTime());
    }
    
    @override
    void dispose(){
    if(_timer.isActive) _timer.cancel();
    super.dispose();
    }
    }
    

    Then when user taps the button call _timer.cancel(); to stop the Timer

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum