Update variables data using Set State

Issue

I am trying to update the two variables when app resumes, the variables are minutes and hours. Right now when i resume the app the values don’t get updated.

@override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addObserver(this);
    dateTimeNow = DateTime.parse('${prefs.getString('startTime')}');
    startedDateTime = DateTime.now();

    minutes = startedDateTime.difference(dateTimeNow).inMinutes % 60;
    hours = startedDateTime.difference(dateTimeNow).inHours;

    if (minutes < 0) {
      minutes = 0;
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive:
        print("Inactive");
        break;
      case AppLifecycleState.paused:
        print("Paused");
        break;
      case AppLifecycleState.resumed:
        print('resumed');
        setState(() { // trying to updated
          minutes = startedDateTime.difference(dateTimeNow).inMinutes % 60;
          hours = startedDateTime.difference(dateTimeNow).inHours;
        });
        break;
    }
  }

Solution

It seems that you are not updating the startedDateTime value. You only set it during the first initialization of the state but you are not updating the value later. Meaning, even after updating your values with didChangeAppLifecycleState, the startedDateTime is still the same, hence the minutes or hours values remain the same.

Try to do something like this:

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
  super.didChangeAppLifecycleState(state); // <-- Add this as well
  switch (state) {
    <...>
    case AppLifecycleState.resumed:
      print('resumed');
      setState(() {
        // trying to updated
        startedDateTime = DateTime.now(); // <-- Update the value
        minutes = startedDateTime.difference(dateTimeNow).inMinutes % 60;
        hours = startedDateTime.difference(dateTimeNow).inHours;
      });
      break;
  }
}

Answered By – mkobuolys

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.