flutterflutter-state

addPostFrameCallback vs scheduleFrameCallback


So, I was wondering, when to use WidgetsBinding.instance.addPostFrameCallback and WidgetsBinding.instance.scheduleFrameCallback for setState, as according to the documentation, the first one doesn't initiate a frame on its own, while if we asynchronously call setState then it might get called during the build of another widget, which can cause not to update the other widget, so for it, we add it as a "post frame" callback, but if it is called not during a build, then it will not initiate the next frame on its own, i.e we cannot always wrap async setState calls with it, as there is a good chance it might be called during not a build, that's when I found scheduleFrameCallback, and according to its documentation, I think it schedules the next frame and adds its as a callback to it, i.e it also initiates a frame. So is it always better to call setState inside it, or is it something else?


Solution

  • It seems to me that to get the best of both worlds (guaranteed no race condition, plus guaranteed run; at a normally small performance cost) you could scheduleFrameCallback() with an empty callback function, after an addPostFrameCallback() with the function you (for instance) really need to happen after a (or a/the impending) frame