5

I have an app that needs a persistent, across multiple screen timer feature in it, which can be launched from one or two different screens. I can build a timer widget and countdown part. But I can't seem to figure it out how to keep it running and floating across all screens, meaning while I tap out, it can still show in different other screens? Or do I need to rebuild it with a global state at every screen I go to?

I’m thinking A small persistent modal sheet at bottom? But the persistent part have had me struggling for a week now.

Do I use Stack? I just don’t know where to start on the part that can stay across all screens.

Please help, guys. thank you in advance!!!

lycheelichi
  • 185
  • 1
  • 2
  • 9

1 Answers1

5

Create a dart file named countdown_timer.dart

In this file add a global variable.

int secondsLeft = 500; //add time you wish to countdown in seconds

By global i mean not inside a class. Now create a stateful widget below this named CountdownTimer. Add a periodic timer with duration 1 second. On each second update reduce the global secondsLeft and use seconds left to display the countdown. If seconds left is less than 0 then stop the periodic timer. Your class would looks something like this

import 'dart:async';
import 'package:flutter/material.dart';
int secondsLeft = 500;

class CountDownTimer extends StatefulWidget {
  const CountDownTimer({Key? key}) : super(key: key);


  @override
  State<CountDownTimer> createState() => _CountDownTimerState();
}

class _CountDownTimerState extends State<CountDownTimer> {
  late Timer countDown;
  
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    countDown = Timer.periodic(Duration(seconds:1), (timer){
      secondsLeft--;
      if(secondsLeft <= 0)
      {
        timer.cancel();
      }
      setState((){});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text("$secondsLeft seconds left");
  }
}

You can now use CountDownTimer() in any class and it will return consistent countdown.

Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
  • 1
    Yes it does the job when you on that page thanks, but when you navigate back or moving to another page, the error comes `FlutterError (setState() called after dispose(): _CountDownTimerState#cfa61(lifecycle state: defunct, not mounted) ` – Muhammad Faisal Nov 09 '22 at 09:31
  • **Edit:** [found solution here](https://stackoverflow.com/a/63593001/9039350) – Muhammad Faisal Nov 09 '22 at 10:23
  • 2
    Um, btw how to prevent the Timer Re-initialized? Like when the Timer started in Page B and ticking back every 1 second, then if i go back to Page A, then the tick added to become 2 every second and so on.. How to prevent this? – Muhammad Faisal Nov 10 '22 at 04:54