Home > Mobile >  Update variables data using Set State
Update variables data using Set State

Time:03-25

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

CodePudding user response:

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

CodePudding user response:

Kindly add super.didChangeAppLifecycleState(state); at the end of didChangeAppLifecycleState() method as like this:

 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;
    }
        super.didChangeAppLifecycleState(state);
  }

And also override the dispose method:

void dispose() {
    WidgetsBinding.instance!.removeObserver(this);
    super.dispose();
  }
  • Related