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

Time:02-08

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);

  }

CodePudding user response:

I highly recommend you to use a Stream for this purpose. For example:

Stream<int> tick({required int ticks}) {
return Stream.periodic(Duration(seconds: 1), (x) => ticks   x   1)
    .take(ticks);

}

That's very similar to what you can find in this Bloc Tutorial - link

CodePudding user response:

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
  }
  •  Tags:  
  • Related