Life cycle in flutter

前端 未结 8 819
予麋鹿
予麋鹿 2020-12-07 10:48

Does flutter have a method like Activity.resume() which can tell developer the user has gone back to the activity.

When I pick the data from internet in

相关标签:
8条回答
  • 2020-12-07 11:16

    There's an example here: https://github.com/flutter/flutter/blob/master/examples/layers/services/lifecycle.dart

    You need to use WidgetsBindingObserver

    0 讨论(0)
  • 2020-12-07 11:25

    Only StatefulWidget hold state . Lifecyle of it is as follow

    • createState () : When we build a new StatefulWidget, this one calls createState() right away and this override method must exist
    • initState() :it is the first method called after the Widget is created.This is our equivalent to onCreate() and viewDidLoad()
    • didChangeDependencies() : This method is called immediately after initState() on the first time the widget is built
    • build() : called right after didChangeDependencies(). All the GUI is render here and will be called every single time the UI needs to be render
    • didUpdateWidget() : it’ll be called once the parent Widget did a change and needs to redraw the UI
    • deactivate() : framework calls this method whenever it removes this State object from the tree
    • dispose() :is called when this object and its State is removed from the tree permanently and will never build again.

    AppLifecycleState are as follows

    • inactive - The application is in an inactive state and is not receiving user input. iOS only

    • paused - The application is not currently visible to the user, not responding to user input, and running in the background.

    • resumed - The application is visible and responding to user input.

    • suspending - The application will be suspended momentarily. Android only

    0 讨论(0)
  • 2020-12-07 11:28

    I don't think flutter app lifecycle callbacks are going to help you here. You can try this logic.

    In 1st page (when navigating to 2nd page)

    Navigator.push(context, MaterialPageRoute(builder: (context) => Page2())).then((value) {
      print("Value returned form Page 2 = $value");
    };
    

    In 2nd page (when navigating back to 1st page)

    Navigator.pop(context, returnedValue);
    

    Lifecycle callback

    void main() => runApp(HomePage());
    
    class HomePage extends StatefulWidget {
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this);
      }
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        super.didChangeAppLifecycleState(state);
        print("Current state = $state");
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(title: Text("Lifecycle")),
            body: Center(child: Text("Center"),),
          ),
        );
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
    }
    
    0 讨论(0)
  • 2020-12-07 11:29

    Constructor

    This function is not part of the life cycle, because this time the State of the widget property is empty, if you want to access the widget properties in the constructor will not work. But the constructor must be to the first call.

    createState

    When Flutter is instructed to build a StatefulWidget, it immediately calls createState()

    Init State

    Called when this object is inserted into the tree.

    When inserting the render tree when invoked, this function is called only once in the life cycle. Here you can do some initialization, such as initialization State variables.

    setState

    The setState() method is called often from the Flutter framework itself and from the developer.

    didChangeDependencies

    Called when a dependency of this [State] object changes.

    didUpdateWidget

    Called whenever the widget configuration changes.

    deactivate

    Called when this object is removed from the tree. Before dispose, we will call this function.

    dispose

    Called when this object is removed from the tree permanently.

    didChangeAppLifecycleState

    Called when the system puts the app in the background or returns the app to the foreground.

    Here is a good detail document: https://www.bookstack.cn/read/flutterbyexample/aebe8dda4df3319f.md

        import 'package:flutter/material.dart';
    
        class ScreenLifecyle extends StatefulWidget {
        ScreenLifecyleState state;
    
        //createState(): When the Framework is instructed to build a StatefulWidget, it immediately calls createState()
        @override
        State<StatefulWidget> createState() {
            // TODO: implement createState
            return ScreenLifecyleState();
        }
        }
    
        class ScreenLifecyleState extends State<ScreenLifecyle> {
        /*
        mounted is true: When createState creates your state class, a buildContext is assigned to that state.
        BuildContext is, overly simplified, the place in the widget tree in which this widget is placed.
        Here's a longer explanation. All widgets have a bool this.mounted property.
        It is turned true when the buildContext is assigned. It is an error to call setState when a widget is unmounted.
        mounted is false: The state object can never remount, and an error is thrown is setState is called.
        */
    
        /*
        This is the first method called when the widget is created (after the class constructor, of course.)
        initState is called once and only once. It must called super.initState().
        */
        @override
        void initState() {
            // TODO: implement initState
            super.initState();
            print("initState");
        }
    
        /*
        This method is called immediately after initState on the first time the widget is built.
        */
        @override
        void didChangeDependencies() {
            // TODO: implement didChangeDependencies
            super.didChangeDependencies();
            print("didChangeDependencies");
        }
    
        /*
        build(): This method is called often. It is required, and it must return a Widget.
        */
        @override
        Widget build(BuildContext context) {
            print("build");
    
            // TODO: implement build
            return Container();
        }
    
        /*
        If the parent widget changes and has to rebuild this widget (because it needs to give it different data),
        but it's being rebuilt with the same runtimeType, then this method is called.
        This is because Flutter is re-using the state, which is long lived.
        In this case, you may want to initialize some data again, as you would in initState.
        */
        @override
        void didUpdateWidget(ScreenLifecyle oldWidget) {
            print("didUpdateWidget");
    
            // TODO: implement didUpdateWidget
            super.didUpdateWidget(oldWidget);
        }
    
        @override
        void setState(fn) {
            print("setState");
    
            // TODO: implement setState
            super.setState(fn);
        }
    
        /*
        Deactivate is called when State is removed from the tree,
        but it might be reinserted before the current frame change is finished.
        This method exists basically because State objects can be moved from one point in a tree to another.
        */
        @override
        void deactivate() {
            // TODO: implement deactivate
            print("deactivate");
            super.deactivate();
        }
    
        /*
        Dispose is called when the State object is removed, which is permanent.
        This method is where you should unsubscribe and cancel all animations, streams, etc.
        */
        @override
        void dispose() {
            // TODO: implement dispose
            super.dispose();
         }
    
           @override
            void didChangeAppLifecycleState(AppLifecycleState state) {
                super.didChangeAppLifecycleState(state);
                switch (state) {
                case AppLifecycleState.inactive:
                    print('appLifeCycleState inactive');
                    break;
                case AppLifecycleState.resumed:
                    print('appLifeCycleState resumed');
                    break;
                case AppLifecycleState.paused:
                    print('appLifeCycleState paused');
                    break;
                case AppLifecycleState.suspending:
                    print('appLifeCycleState suspending');
                    break;
                }
            }
    
      }
     
    
    0 讨论(0)
  • 2020-12-07 11:31
    1. createState(): When we create a stateful widget, the Flutter framework instruct to createState() method.

      @override _DeveloperLibsWidgetState createState() => _DeveloperLibsWidgetState();

    2.mounted(true/false): Once we create a State object, the framework mounted the State object by associating it with a BuildContext before calling initState() method. All widgets have a bool mounted property. It is turned true when the buildContext is assigned.

    bool get mounted => _element != null;
    
    1. initState(): This is the first method called when a stateful widget is created after the class constructor. The initState() is called only once. It must called super.initState().

      @override initState() { super.initState(); // TO DO }

    2. didChangeDependencies(): This method is called immediately after initState() method on the first time the widget is built.

      @protected @mustCallSuper void didChangeDependencies() {

      }

    3. build(): it shows the part of the user interface represented by the widget. The framework calls this method in several different situations: After calling initState() method. The framework always calls build() method after calling didUpdateWidget After receiving a call for setState to update the screen.

      @override Widget build(BuildContext context, MyButtonState state) { return Container(color: const Color(0xFF2DBD3A));
      }

    4. didUpdateWidget(Widget oldWidget): If the parent widget change configuration and has to rebuild this widget. But it's being rebuilt with the same runtimeType, then didUpdateWidget() method is called.

      @mustCallSuper @protected void didUpdateWidget(covariant T oldWidget) {

      }

    5. setState(): This method is called from the framework and the developer. We can change the internal state of a State object and make the change in a function that you pass to setState().

      @override _DeveloperLibsWidgetState createState() => _DeveloperLibsWidgetState();

    6. deactivate(): This is called when State is removed from the widgets tree, but it might be reinserted before the current frame change is finished.

      @protected @mustCallSuper void deactivate() { }

    7. dispose(): This is called when the State object is removed permanently. Here you can unsubscribe and cancel all animations, streams, etc.

      @protected @mustCallSuper void dispose() { assert(_debugLifecycleState == _StateLifecycle.ready); assert(() { _debugLifecycleState = _StateLifecycle.defunct; return true; }()); }

    0 讨论(0)
  • 2020-12-07 11:35

    App Lifecycle

    For LifeCycle, you need to use WidgetsBindingObserver it works when the app goes on foreground and background.

    import 'package:flutter/widgets.dart';
      class YourWidgetState extends State<YourWidget> with WidgetsBindingObserver {
    
           @override
          void initState() {
            super.initState();
            WidgetsBinding.instance.addObserver(this);
          }
    
    
          @override
          void dispose() {
            WidgetsBinding.instance.removeObserver(this);
            super.dispose();
          }
    
    
           @override
          void didChangeAppLifecycleState(AppLifecycleState state) {
            if (state == AppLifecycleState.resumed) {
               //do your stuff
            }
          }
        }
    

    But in my case, i was unable to catch the situation of OnResume when I move from one screen to another. so below code working similarly as startActivityForResult.

    use this code when your reaching to another activity

    Navigator.push(context,
                  MaterialPageRoute(builder: (context) => ProductDetails(pid: productList[index]["pid"],),
                      settings: RouteSettings(name: '/productdetail')),).then((value){
                        setState(() {
                          length=value;
                        });
                        debugPrint('CHECK BACK FROM DETAIL $length');
                });
    

    when you press back

    onPressed: (){Navigator.pop(context,length);}
    
    0 讨论(0)
提交回复
热议问题