13

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.

Craig Carr
  • 403
  • 5
  • 11
  • 3
    https://oleksandrkirichenko.com/blog/delayed-code-execution-in-flutter/ might help you. – NBM Jul 30 '21 at 04:34

1 Answers1

16

The link in the comment posted by @NBM (https://oleksandrkirichenko.com/blog/delayed-code-execution-in-flutter) pretty much answers the question. I will provide a brief explanation here for posterity.

  • The Future.delayed(Duration.zero, () {}) approach is using the behavior of Dart's event queue to delay execution until the next event loop iteration, at which point it is safe to access context since the widget is guaranteed to be built.

  • The SchedulerBinding.instance.addPostFrameCallback((_) {}); approach is specific to Flutter and is tied to the widget's lifecycle. The end effect is still to wait until the next event loop iteration, but semantically this approach makes more sense since we are solving a Flutter problem using a Flutter mechanism.

Craig Carr
  • 403
  • 5
  • 11