Timer still running after cancel()

814 views Asked by At

I am making a digital clock in flutter. I am using Timer() to print current time and update UI every second, using Riverpod for UI. The issue is that when I click back and exit the page, the timer successfully closes. But this 'Error Code' is recurring every second. maybe Timer is Not infact closed at all ? How stop it from running in backgound.

my full code is:


    
class TimerClockQuestion extends ConsumerWidget {
  final myStateProviderTime2 = StateProvider((ref) => 'state time');

  Timer? timerClock2;
  String currentTime = '12:00 AM';

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    runTimerClock(ref);
    currentTime = ref.watch(myStateProviderTime2);


    return Scaffold(
      body: Center(
        child: Text(
          currentTime ,
          style: TextStyle(fontSize: 50, color: Colors.white38),
        ),
      ),
    );
  }

  void runTimerClock(WidgetRef ref){
    timerClock2?.cancel();
    timerClock2 = Timer.periodic(Duration(seconds: 1), (timer) {
      currentTime = DateFormat('hh:mm:ss a').format(DateTime.now());
      ref.read(myStateProviderTime2.notifier).state = currentTime;
      print(currentTime);
    });
  }
}


Error message is

Error: Looking up a deactivated widget's ancestor is unsafe.
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49  throw_
packages/flutter/src/widgets/framework.dart 4241:9                                                                         <fn>
packages/flutter/src/widgets/framework.dart 4254:14                                                                        [_debugCheckStateIsActiveForAncestorLookup]
packages/flutter/src/widgets/framework.dart 4286:12                                                                        getElementForInheritedWidgetOfExactType
packages/flutter_riverpod/src/framework.dart 101:22                                                                        containerOf
packages/flutter_riverpod/src/consumer.dart 607:59                                                                         read
packages/riverpod_prc/ponds/state/timer_clock_question.dart 30:3                                                           <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/isolate_helper.dart 80:17       <fn>
  
1

There are 1 answers

0
Gpack On BEST ANSWER

The problem is that your timer gets cancelled every time your widget builds but not when it's diposed (when you click on back). The solution would be to use a stateful widget, store the timer in the state and cancel it in the dispose method.