Flutter - Always execute a function when the page appears

后端 未结 5 1172
暗喜
暗喜 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:32

    You can use RouteObserves if you want to execute some function whenever your page appears, you will have to implement RouteAware on the page where you want to run execute the function whenever the screens appears, you're gonna have to do something like this on ur Page1

    final RouteObserver routeObserver = RouteObserver(); // add this on your main class
    void main() {
      runApp(MaterialApp(
        home: Container(),
        navigatorObservers: [routeObserver], // add observer here;
      ));
    } 
    
    
    
    
    
    // your page where func should run whenever this page appears
    class MyHomePage extends StatefulWidget with RouteAware {
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State {
      String nameScreen = "";
    
      String name() {
        return 'foo1';
      }
    
      @override
      void initState() {
        super.initState();
        this.nameScreen = "From initState";
    
      }
    
     @override
      void didChangeDependencies() {
        super.didChangeDependencies();
        routeObserver.subscribe(this, ModalRoute.of(context));
      }
    
      @override
      void dispose() {
        routeObserver.unsubscribe(this);
        super.dispose();
      }
    
    // implementing RouteAware method
    void didPush() {
    // Route was pushed onto navigator and is now topmost route.
        name(); // your func goes here
      }
    
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Page 1'),
            backgroundColor: Color(0xFF26C6DA),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                RaisedButton(
                  child: const Text('go to Page2'),
                  onPressed: () async {
                    //dispose(); ///No need for dispose
                    String result = await Navigator.of(context).pushNamed('/page2');
    
                      setState((){
                        this.nameScreen = result;
                      });
    
                  },
                ),
                Text(
                  '$nameScreen',
                ),
              ],
            ),
          ),
        );
      }
    }
    

    you can head over to this link for more explanation https://api.flutter.dev/flutter/widgets/RouteObserver-class.html

提交回复
热议问题