How can I run a function whenever a page is loaded in flutter?

429

Solution 1

WidgetsBinding offers a way to add a one time post frame callback.

WidgetsBinding.instance.addPostFrameCallback((_) {
  // executes after build
})

As this callback will only be called a single time, you will want to add it every time you build:

@override
Widget build(BuildContext context) {
  WidgetsBinding.instance.addPostFrameCallback((_) => afterBuild);
  return Container(); // widget tree
}

void afterBuild() {
  // executes after build is done
}

Solution 2

Isn't it possible to use DidChangeDependencies() function to solve your problem? Since it's called immediately after initState() is done :)

     @override
  void didChangeDependencies() {
    super.didChangeDependencies();
//Code here
}
Share:
429
Tobias H.
Author by

Tobias H.

Updated on December 04, 2022

Comments

  • Tobias H.
    Tobias H. over 1 year

    I think the title sumes it up pretty well, how do I run some peice of code when ever a page is loaded in flutter? Or how to set the scroll ofset of a listview to be a certain % of the page using : "MediaQuery.of(context).size.height/3", the reason this dosn't work is because I can't use the (context) in the listview, because there's no context yet. But if it's not posible to do the listview thing, then I would also be able to do with some code that runs when ever the page loades :)

  • Tobias H.
    Tobias H. over 3 years
    This works, but I have to open the page twice for anything to happen, even if I put the afterBuild() in the main.dart. Idk why, do you?