Flutter: Run method on Widget build complete

KingLagalot picture KingLagalot · Mar 24, 2018 · Viewed 94k times · Source

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?

Answer

Thomas picture Thomas · Jun 4, 2018

You could use

https://github.com/slightfoot/flutter_after_layout

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() {
    super.initState();
    WidgetsBinding.instance
        .addPostFrameCallback((_) => yourFunction(context));
  }