While developing your Flutter app, you may need to check something after the widget build is completed. For example, you may want to check whether the user is authenticated on any screen after the UI is fully loaded. There can be many tricky solutions to deal with this issue for example putting a delay in your page. But in this tutorial, we’ll see the right way to call method after build in Flutter using the addPostFrameCallback callback.
In this tutorial, we’ll try to print a message as soon as the build function is completed which looks like this:
Here’s what we’ll cover:
The Problem
Flutter has got several lifecycle methods that allow you to take action at a specific point such as initState
, build
, dispose
, setState
, and so on. These methods are very helpful. For example, you could start all initialization inside the initState
method and garbage the unwanted things inside the dispose
method. But there is no dedicated method (part of lifecycle) to know when the build is completed. This can be crucial for some of your app features.
How to Call Method after Build in Flutter
To call method after build is completed, the idea is to use the addPostFrameCallback callback and add your method inside it. As its name suggests it allows you to register a callback after the last frame of your page is drawn.
Steps
Step 1: Make sure you have StatefulWidget
.
Step 2: Add the initState
method to your page.
Step 3: Inside the initState, call the WidgetsBinding.instance and then chain the addPostFrameCallback callback.
Step 4: Inside the addPostFrameCallback, write a method that you want to call after build is completed.
Step 5: Restart your app.
Code Example
@override void initState() { // TODO: implement initState super.initState(); WidgetsBinding.instance?.addPostFrameCallback((_) { // do something print("Build Completed"); }); }
Conclusion
In this tutorial, we learned how to call method after build in Flutter using the addPostFrameCallback callback. Basically, you add the callback that gets fired after the page layout is fully drawn.
Would you like to check other interesting Flutter tutorials?