In my application I have a few values that on startup I want to be able to refresh and reload from SharedPreferences, and make some adjustments to in the process if necessary. I'm currently facing the issue of actually grabbing these values consistently on startup however. Originally I had all these functions in my initState() function thinking this would make the values always reload on boot, but this behaviour doesn't seem to be consistent.

My first attempt

My get functions are all based on a variation of this:

Function

Then I tried using addPostFrameCallback where I did the following:

addPostFrameCallback

This last implementation seems to run constantly every half second for some reason, and I can't exactly figure out why this is happening. Is there any solution to this, or any other solution I could try?


Solution 1: Harish Sharma

as you are calling setState inside build method, so build method is rendering again and again in infinite loop. if you need to do setState after screen open you can override didChangeDependencies method like below -

@override
  void didChangeDependencies() {
    super.didChangeDependencies();
    WidgetsBinding.instance?.addPostFrameCallback((_) async {
      setState(() {
        // Write your code here
      });
    });
  }