Search code examples
fluttertimerbackground

Run Timer in Background in flutter


I want Run Timer In Background also even if user closed app. And don't stop until user do not stops even app closed. I tried stream but it stop when app closed. So Please Help me. Thanks in advance.


Solution

  • Thank you for giving answer

    But I find solution like current time save in local device using SharedPreferences and when user open app again then find difference between saved time and currenttime show in my app

    here is my code

        startTimer() {
        timerStream = stopWatchStream();
        timerSubscription = timerStream.listen((int newTick) {
          String time = _sharedPreferences.getString("time");
          Duration duration = DateTime.now().difference(DateTime.parse(time));
    
          setState(() {
            hoursStr = ((duration.inSeconds / (60 * 60)) % 60)
                .floor()
                .toString()
                .padLeft(2, '0');
            minutesStr =
                ((duration.inSeconds / 60) % 60).floor().toString().padLeft(2, '0');
            secondsStr =
                (duration.inSeconds % 60).floor().toString().padLeft(2, '0');
          });
        });
      }