Flutter Logo

Flutter: how to perform action after the build of a widget is completed?

In Flutter, sometimes you want to perform an action after the build process of a widget is completed. For example, you may need to update the view or start an animation once the widget is displayed on the screen. To achieve this, Flutter provides the addPostFrameCallback method, which allows you to execute a callback after the last frame of a widget’s build process is drawn.

addPostFrameCallback is a method of the SchedulerBinding class, which is the central class that schedules tasks and controls the behavior of the framework. By calling SchedulerBinding.instance.addPostFrameCallback, you can register a callback that will be executed once the build process of your widget is completed.

Here’s an example of how you can use addPostFrameCallback to update the view after a widget is built:

class MyWidget extends StatefulWidget {
   _MyWidgetState createState() => _MyWidgetState();

 class MyWidgetState extends State {   
  Widget build(BuildContext context) {
    SchedulerBinding.instance.addPostFrameCallback(() {
      // Perform an action after the build is completed
    return Container();

In this example, MyWidget is a stateful widget. Inside the build method of _MyWidgetState, you can call SchedulerBinding.instance.addPostFrameCallback and pass a callback; the callback will be handled after the build process is completed.

It’s important to note that addPostFrameCallback will be executed only once. If you need to perform an action multiple times, you’ll need to register a new callback each time. Additionally, you should avoid using addPostFrameCallback inside a hot reload cycle, as it can lead to unexpected behavior.

In conclusion, addPostFrameCallback is a useful method for performing actions after the build process of a widget is completed. By using this method, you can update the view or start animations at the appropriate time.

Related Posts