Home > Blockchain >  addPostFrameCallback runs constantly when I only want it to run once
addPostFrameCallback runs constantly when I only want it to run once

Time:06-18

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?

CodePudding user response:

You're adding addPostFrameCallback in the build method, which means the method is constantly triggering a rebuild, which causes it to keep triggering.

If you want to add your addPostFrameCallback you should add it in the initState method instead of the build method.

@override 
void initState() {
  super.initState();
  WidgetsBinding.instance.addPostFrameCallback((_) async {
      _getLastUsedDate();
      // Rest of your code
  });
}

If you can, avoid putting method calls in the build method, since they will run on every rebuild, which you do not want in most cases.

CodePudding user response:

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
      });
    });
  }
  • Related