As seen in https://stackoverflow.com/a/49458289/5150593, there are essentially two ways to access BuildContext
after initially rendering a widget in Flutter (i.e. in initState
):
Future.delayed(Duration.zero, () {
// context can be used here...
});
and
SchedulerBinding.instance.addPostFrameCallback((_) {
// context can be used here...
});
What difference is there between the two approaches? Is there any advantage to using one approach over the other? Are there any hidden side effects that I'm not seeing?
From my own exploration, if I use both methods in the same widget's initState
, the order in which the callbacks are executed is the same as the order in which the callbacks are registered. I looked at the Flutter source code for Future.delayed
and SchedulerBinding.instance.addPostFrameCallback
but I don't really understand what's going on.