Flutter: Run method on Widget build complete

flutter call function after build
flutter call function on load
flutter addpostframecallback
flutter widget lifecycle
flutter initstate
flutter lifecycle methods
flutter call method on statefulwidget
flutter build complete callback

I would like to be able to run functions once a Widget has finished building/loading but I am unsure how. My current use case is to check if a user is authenticated and if not, redirect to a login view. I do not want to check before and push either the login view or the main view, it needs to happen after the main view has loaded. Is there anything I can use to do this?

You could use


which executes a function only one time after the layout is completed. Or just look at its implementation and add it to your code :-)

Which is basically

  void initState() {
        .addPostFrameCallback((_) => yourFunction(context));

Add run once after first build layout · Issue #29543 · flutter/flutter , Every time you need to use the context but run once the code you .com/​questions/49466556/flutter-run-method-on-widget-build-complete The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

UPDATE: Flutter v1.8.4

Both mentioned codes are working now:


        .addPostFrameCallback((_) => yourFunction(context));


import 'package:flutter/scheduler.dart';

SchedulerBinding.instance.addPostFrameCallback((_) => yourFunction(context));

How to call a function on start in Flutter stateless widgets, How to call a function on start in Flutter stateless widgets. Dane Mackier widget​.onInit(); } super.initState(); } @override. Widget build(BuildContext context) { Run async operation on widget creation. I often see people trying to execute an asyncronous operation in the render method of a widget. This doesn't work, but is also bad because it gets called every time the state or properties get updated. It can lead to a lot of unneccessary work. A StatefulWidget needs to be used to do this properly.

Flutter 1.2 - dart 2.2

According with the official guidelines and sources if you want to be certain that also the last frame of your layout was drawned you can write for example:

import 'package:flutter/scheduler.dart';

void initState() {
   if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
        SchedulerBinding.instance.addPostFrameCallback((_) => yourFunction(context));

Flutter: Run method on Widget build complete, You could use. https://github.com/slightfoot/flutter_after_layout. which executes a function only one time after the layout is completed. Or just  Flutter Stateless widget startup logic. One of the most common scenarios in Mobile development is calling an async function when a new view is shown. In Flutter this can be done using a stateful widget and calling your code in the initState function.

If you are looking for ReactNative's componentDidMount equivalent, Flutter has it. It's not that simple but it's working just the same way. In Flutter, Widgets do not handle their events directly. Instead they use their State object to do that.

class MyWidget extends StatefulWidget{

  State<StatefulWidget> createState() => MyState(this);

  Widget build(BuildContext context){...} //build layout here

  void onLoad(BuildContext context){...} //callback when layout build done

class MyState extends State<MyWidget>{

  MyWidget widget;


  Widget build(BuildContext context) => widget.build(context);

  void initState() => widget.onLoad(context);

State.initState immediately will be called once upon screen has finishes rendering the layout. And will never again be called even on hot reload if you're in debug mode, until explicitly reaches time to do so.

Flutter - addPostFrameCallback, How can I do something once a build is complete? you can trigger it from the initState() or even from the Widget build(BuildContext context)… When you invoke the showDialog() method, you request Flutter to try to find the  The callAsyncFetch function could be an HTTP call, a Firebase call, or a call to SharedPreferences or SQLite, etc. Anything that returns a Future 🔮.. So, can we make the build method async? 🤔

Try SchedulerBinding,

                .addPostFrameCallback((_) => setState(() {
              isDataFetched = true;

Run async operation on widget creation, Run async operation on widget creation I often see people trying to execute an asyncronous operation in the render method of a widget. @override Widget build(BuildContext context) { if (_result == null) { // This is what we  Having a method to run once with context being safe to use. Also related, somehow, is in build method using SchedulerBinding.instance.addPostFrameCallback((_) seems like hack (after_layout package helps with this issue).

build method - State class - widgets library - Dart API, The framework calls this method in a number of different situations: After calling initState. After calling didUpdateWidget. After receiving a call to setState. After a  Write your first Flutter app, part 1 Step 1: Create the starter Flutter app. Create a simple, templated Flutter app, Step 2: Use an external package. In this step, you’ll start using an open-source package named Step 3: Add a Stateful widget. State less widgets are immutable, Step 4:

after_layout, Execute code after the first layout of your widget has been performed, i.e. after the first frame has been displayed. the void afterFirstLayout(BuildContext context) abstract method. extends StatelessWidget { @override Widget build(​BuildContext Analysis was completed with status completed using:. How to implement Flutter asynchronous processing. As most production smartphone applications access DBs and APIs, asynchronous processing is required. There is two Async Widgets in Flutter Official site. Since I am a beginner to Dart and Flutter, I do not know which one to use, but first I wrote to use StreamBuilder.

How to Build Widgets with an Async Method Call, You want to return a widget in a build method… But your data comes from an async function! class MyWidget extends StatelessWidget { @  In Flutter, a route is just a widget. Navigate to a new route using the Navigator. This recipe uses the following steps: The next few sections show how to navigate between two routes, using these steps: Create two routes. Navigate to the second route using Navigator.push(). Return to the first route using Navigator.pop().

  • It's unlikely that you want to start the login process in build. Build can be called at any time multiple times.
  • Look at this: stackoverflow.com/questions/49359706/redirect-on-app-load
  • Thanks @thomas your ans is very helpful for me. i work on this before two days and now they and after reading your ans. again thank you very mush good job
  • See @anmol.majhail answer: WidgetsBinding.instance.addPostFrameCallback((_) => yourFunciton(context)); is not longer working
  • Hi @Thomas, it's not working for me. still get null exception. any idea ?
  • Second one no longer works. NoSuchMethodError (NoSuchMethodError: The method 'addPostFrameCallback' was called on null. Receiver: null
  • Now I m curious why doesn't it work for one of you
  • Please explain where I should call this code
  • @EliaWeiss - it Depends on your use case - This is just a way to call a function on Widgets after the build. typical use will be in init()
  • For me this didn't work, because at initState() time I get schedulerPhase with SchedulerPhase.idle value ... what it actually worked was to add that check within build()
  • From my example, you can use StatefulWidget class to handle it's State object just like a StatelessWidget but I highly not recommend it. I'm not yet found any issue but please try to implement everything inside State object first
  • flutter.dev/docs/cookbook/networking/fetch-data Google recommends to call data fetching on initState(). Therefore there is no issue with this solution, in fact this should be the accepted answer.
  • In React Native data fetching can be doing in componentWillMount just before layout rendering. Flutter provides simpler solution. initState is enough for both data fetching and on layout rendered if we know how to doing it properly
  • componentWillMount will be deprecated soon. Therefore fetching will be done after the component has been mounted and constructed.