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!
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.
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.
after_layout | Flutter Package
Brings functionality to execute code after the first layout of a widget has been performed, i.e. after the first frame…
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.
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…
I’ll be posting more content soon, so stay tuned. I’m open to suggestions of subjects to talk about.