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

Issue

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?

*.dart

activeTimer(value) {
    print(value);

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

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

  }

Solution

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;
@override
  initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    app_start = DateTime.now();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);

    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(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 *