'widget rebuilds and state resets in flutter app

I am trying to get the app to save the endDate of the fasting period. So, user sets the time to fast, whenever they check back the app has to display the date and time. I tried with sharedPrefs and hive. But my widget rebuilds and the time resets. How to implement it so the value persists? I am just learning flutter, and do not have a programmer's background. :/ help appreciated very much!

class TimerPage extends StatefulWidget {
const TimerPage({Key? key}) : super(key: key);

@override
TimerPageState createState() => TimerPageState();

static late SharedPreferences _preferences;

static Future init() async =>
  _preferences = await SharedPreferences.getInstance();
}

class TimerPageState extends State<TimerPage> {
final boxFastTime = Hive.box('fast_time');
final DateRangePickerController datePickerController = 
DateRangePickerController();

DateTime startTime = DateTime.now();
DateTime endTime = DateTime.now().add(const Duration());
Duration fastDuration = const Duration();
bool? isFasting;

Future<bool?> fastTrue() async {
DateTime finishTime = endTime.add(fastDuration);
if(finishTime.compareTo(DateTime.now())>0){
  setState(() {
    TimerPage._preferences.setBool('isFasting', false);
   isFasting = false;
  });
  showMessage(Languages.of(context)!.yourFastTimeFinished + 
endTime.toString());
} else {
  setState(() {
    TimerPage._preferences.setBool('isFasting', true);
    isFasting = true;
  });
}
return  TimerPage._preferences.getBool('isFasting');
}

@override
@mustCallSuper
void initState(){
fastTrue();
Hive.openBox('fast_hive');
boxFastTime.get('endTime');
 }

and then in the widget I set the values:

@override
 Widget build(BuildContext context) {
 var fastHive = boxFastTime.get('endTime');
 String formattedDate = DateFormat('yyyy-MM-dd 
 HH:mma').format(endTime);
 return Scaffold(
       blahblah:
     ElevatedButton(
       onPressed: () async {
          setState(() {
          fastDuration= const Duration(hours: 14);
          endTime = DateTime.now().add(fastDuration);
          boxFastTime.put('hours', fastDuration);
          boxFastTime.put('endTime', endTime);
          boxFastTime.put('startTime', DateTime.now());
          TimerPage._preferences.setBool('isFasting', true);
          });
          addNotification(startTime.add(const 
               Duration(hours:14)).hour, startTime.add(const 
                  Duration(hours: 14)).minute);
                        
         showMessage(Languages.of(context)!.yourFastTimeIsSet);
                          },
         child: const Text('14:10'),
                        style: Constants.buttonStyle,
                      ),)}

I also call SharedPreferences.init() in my main() and open the hive box as well.

I have a Text widget, which displays the DateTime.now(), but when user taps on the button it displays the fast endTime. However, whenever, I switch to different screen and go back to timerPage everything resets. How to keep the value saved? :( Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source