Tobias H.
Tobias H.

Reputation: 494

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

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 :)

Upvotes: 1

Views: 1817

Answers (2)

Fluzzy
Fluzzy

Reputation: 81

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
}

Upvotes: 1

Çağrı Aydın
Çağrı Aydın

Reputation: 46

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
}

Upvotes: 2

Related Questions