How to Schedule after build callbacks in Flutter

Rodrigo Bastos
3 min readFeb 21, 2020

If you develop Flutter applications for a while, or even if you are a casual Flutter developer you probably encounter yourself wanting to do some kind of action that uses the context (show a dialog for example) right when you build your widget. And if you tried, i know you failed, because Flutter has some odd behaviors regarding to this. But don’t worry, by the end of this article you’ll learn why Flutter behavior in this way and you’ll be able to show as many dialogs as you want :).

Hop on soldier, you are about to be Flutterized!

# Problem

Let’s suppose you want to open a dialog with some kind of message to the user right when the user navigate to one of your pages. The logical think to try to do is to just do something like that:

But if you try this you will FAIL miserably. And Flutter will tell you that with a little smile and a wonderful Red Screen of Death.

And you will see on the console:

That message is basically telling that you are trying to use the BuildContext of the widget before the widget is built completely. Flutter don’t let you mess with the context until the build method is done.

# Solution

Flutter takes but it gives too :). To solve our problem, Flutter let us Schedule a Callback to be executed right when the build method finishes. Basically wrap your code around a addPostFrameCallback and you would be good to go.

You can even put this code inside the build method. It will work just fine.

# Another good Solution

If you didn’t like the solution #1 don’t worry, i’m sure you’ll like the number #2.

There’s a great package on pub.dev called after_layout. It comes to make it easier to do what we just did.

If you are an Angular guy or a React guy you are probably used to abuse lifecycle hooks to accomplish specific tasks. This packages kind of give you a lifecycle hook that will be executed after the build method finishes. You can then put your code inside this method and be happy.

To use the package just add the dependency:

After that you are ready to go, so just create your StatefulWidget and add the mixin AfterLayoutMixin. After adding the mixin you’ll be asked to implement the afterFirstLayout. In this method you put your code that uses the context, and you are guaranteed to use the context safely.

And that’s all guys, thanks for reading, i hope you liked my article, if so please hit the clap button!

I created a repo with examples on how to solve with both approaches mentioned here.

I’ll be posting more content soon, so stay tuned. I’m open to suggestions of subjects to talk about.

--

--