Flutter - Always execute a function when the page appears

后端 未结 5 1111
暗喜
暗喜 2021-01-20 03:56

How could I make the name() function run whenever the Page1 page appeared?

In the code below before going to Page2 I execute t

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 04:38

    Say you want to navigate from page 1 to page 2 and immediately after page 2 loads execute a function in page 2 (useful for showing a dialog immediately when page 2 loads) :

    You can do this by adding in initState or didChangeDependencies of page 2 :

     WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        // Function to execute
      });
    

    If you want to add some logic to put a condition before executing the function, simply push an argument in your page 1 :

    Navigator.of(context).pushNamed("/page-2", arguments : true)
    

    Finnaly the code in page 2 becomes:

     _functionToExecute(){
      print("done");
      }
     @override
     void didChangeDependencies() {
     
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        if(ModalRoute.of(context).settings.arguments)
        _functionToExecute()
      });
     }
    

提交回复
热议问题