简体   繁体   中英

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

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
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM