How can I get a value from an if statement and work out the difference


I have a function that checks if a user has the app open or closed. If opened take the current time and store it in a variable, if the app is closed, do the same. then it should work out the difference and print it back.

I’m trying to work out how long the user has spent on the app.

I just not sure how to get it to work, I’ve tried to assign it to a global and use it from there but that did not work, I’ve tried sending the values to another function but I keep getting null returned.

What can I do to fix this?


activeTimer(value) {

    if (value == true) {
      print("TRUE 1");
      DateTime dateTimeStart =;
    } else {
      print("FALSE 1");
      DateTime dateTimeEnd =;

  final differenceInDays = dateTimeEnd.difference(dateTimeStart).inMinutes;



You can check when your app is being closed (or placed in background), so just initialize a variable when the app starts and calculate the time when the app closes:

in your main.dart file

late DateTime app_start;
  initState() {

    app_start =;

  void dispose() {


  void didChangeAppLifecycleState(AppLifecycleState state) {
    // check if app is closed -> substract current time from app_start
    // save to local storage or send to cloud or smth

Answered By – Wouter

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *