Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 颤振的生命周期_Flutter - Fatal编程技术网

Flutter 颤振的生命周期

Flutter 颤振的生命周期,flutter,Flutter,Flatter是否有类似于Activity.resume()的方法,可以告诉开发人员用户已返回到活动 当我在第B页从互联网上选取数据并返回到第A页时,我如何才能让第A页知道数据已经准备好了 这里有一个例子: 您需要使用WidgetsBindingObserver createState(): 当框架被指示构建StatefulWidget时,它会立即调用createState() 装载的为真: 当createState创建状态类时,将为该状态分配一个buildContextbuildContex

Flatter是否有类似于
Activity.resume()
的方法,可以告诉开发人员用户已返回到活动

当我在第B页从互联网上选取数据并返回到第A页时,我如何才能让第A页知道数据已经准备好了

这里有一个例子:

您需要使用
WidgetsBindingObserver

  • createState()
    当框架被指示构建StatefulWidget时,它会立即调用
    createState()

  • 装载的
    为真:
    createState
    创建状态类时,将为该状态分配一个
    buildContext
    buildContext
    是小部件树中放置此小部件的位置,过于简化。这里有一个较长的解释。 所有小部件都有一个
    bool this.mounted
    属性。当
    buildContext
    被分配时,它变为true。卸载小部件时调用
    setState
    是错误的

  • initState()
    这是创建小部件时调用的第一个方法(当然是在类构造函数之后)。
    initState
    只调用一次。它必须调用
    super.initState()

  • didChangeDependencies()
    第一次构建小部件时,在
    initState
    之后立即调用此方法

  • build()
    这种方法经常被调用。它是必需的,并且必须返回一个小部件

  • didUpdateWidget(小部件旧小部件)
    如果父窗口小部件发生更改并且必须重新生成此窗口小部件(因为它需要为其提供不同的数据),但正在使用相同的
    runtimeType
    重新生成此窗口小部件,则调用此方法。 这是因为颤振正在重新使用状态,这是长期存在的。在这种情况下,您可能需要再次初始化某些数据,就像在
    initState
    中一样

  • setState()
    此方法通常由框架本身和开发人员调用。它用于通知框架数据已更改

  • 停用()
    当状态从树中删除时调用Deactivate,但它可能在当前帧更改完成之前重新插入。这种方法基本上是存在的,因为状态对象可以从树中的一个点移动到另一个点

  • dispose()
    删除状态对象时,将调用
    dispose()
    ,该状态对象是永久的。此方法用于取消订阅和取消所有动画、流等

  • 装载的
    为假:
    state对象永远无法重新装载,并且在调用
    setState
    时引发错误


  • 我认为Flitter应用程序生命周期回调不会在这方面帮助您。你可以试试这个逻辑

    在第1页中(导航到第2页时)

    在第2页中(导航回第1页时)


    生命周期回调

    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();
      }
    }
    
    void main()=>runApp(HomePage());
    类主页扩展了StatefulWidget{
    @凌驾
    _HomePageState createState()=>\u HomePageState();
    }
    类_HomePageState使用WidgetsBindingObserver扩展状态{
    @凌驾
    void initState(){
    super.initState();
    WidgetsBinding.instance.addObserver(这个);
    }
    @凌驾
    void didchangeAppifecyclestate(AppLifecycleState状态){
    super.didChangeAppLifecycleState(州);
    打印(“当前状态=$state”);
    }
    @凌驾
    小部件构建(构建上下文){
    返回材料PP(
    家:脚手架(
    appBar:appBar(标题:文本(“生命周期”)),
    正文:中心(子项:文本(“中心”),),
    ),
    );
    }
    @凌驾
    无效处置(){
    WidgetsBinding.instance.removeObserver(此);
    super.dispose();
    }
    }
    
    应用程序生命周期

    对于生命周期,您需要使用
    WidgetsBindingObserver
    当应用程序在前台和后台运行时,它可以工作

    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
            }
          }
        }
    
    当你按下按钮时

    onPressed: (){Navigator.pop(context,length);}
    
    构造函数

    此函数不是生命周期的一部分,因为此时小部件属性的状态为空,如果要访问构造函数中的小部件属性,则该函数将不起作用。但是构造函数必须与第一个调用相匹配

    createState

    当指示颤振构建
    StatefulWidget
    时,它会立即调用
    createState()

    初始状态

    将此对象插入树时调用

    在调用时插入渲染树时,此函数在生命周期中仅调用一次。在这里,您可以进行一些初始化,例如初始化状态变量

    设置状态

    setState()
    方法通常从颤振框架本身和开发人员处调用

    didChangeDependencies

    此[状态]对象的依赖项更改时调用

    didUpdateWidget

    每当小部件配置更改时调用

    停用

    从树中删除此对象时调用。 在dispose之前,我们将调用此函数

    处置

    从树中永久删除此对象时调用

    didChangeAppLifecycleState

    当系统将应用程序置于后台或将应用程序返回前台时调用

    以下是一份详细的文档:

    导入“包装:颤振/材料.省道”;
    类ScreenLifecyle扩展StatefulWidget{
    不动产状态;
    //createState():当框架被指示构建StatefulWidget时,它会立即调用createState()
    @凌驾
    状态createState(){
    //待办事项:
    
    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
            }
          }
        }
    
    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');
                });
    
    onPressed: (){Navigator.pop(context,length);}
    
        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;
                }
            }
    
      }
     
    
    bool get mounted => _element != null;
    
    Map results =  await Navigator.of(context).push(MaterialPageRoute(
          builder: (BuildContext context) {
            return new PageB(title: "Choose File");
            },
          ));
    
        if (results != null && results.containsKey('selection')) {
          setState(() {
            _selection = results['selection'];
          });
    
        **//here you can do whatever you want to do with selection variable.**
    
        }
    
    Navigator.of(context).pop({'selection':file});
    
    /// Inherit this State to be notified of lifecycle events, including popping and pushing routes.
    ///
    /// Use `pushNamed()` or `push()` method to track lifecycle events when navigating to another route.
    abstract class LifecycleState <T extends StatefulWidget> extends State<T>
        with WidgetsBindingObserver {
      ResumeResult resumeResult = new ResumeResult();
      bool _isPaused = false;
    
      AppLifecycleState lastAppState = AppLifecycleState.resumed;
    
      void onResume() {}
    
      void onPause() {}
    
      /// Use instead of Navigator.push(), it fires onResume() after route popped
    Future<T> push<T extends Object>(BuildContext context, Route<T> route, [String source]) {
        _isPaused = true;
        onPause();
    
        return Navigator.of(context).push(route).then((value) {
            _isPaused = false;
    
            resumeResult.data = value;
            resumeResult.source = source;
    
            onResume();
            return value;
        });
    }
    
    /// Use instead of Navigator.pushNamed(), it fires onResume() after route popped
    Future<T> pushNamed<T extends Object>(BuildContext context, String routeName, {Object arguments}) {
        _isPaused = true;
        onPause();
    
        return Navigator.of(context).pushNamed<T>(routeName, arguments: arguments).then((value) {
            _isPaused = false;
    
            resumeResult.data = value;
            resumeResult.source = routeName;
    
            onResume();
            return value;
        });
    }
    
      @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.paused) {
          if (!_isPaused) {
            onPause();
          }
        } else if (state == AppLifecycleState.resumed &&
            lastAppState == AppLifecycleState.paused) {
          if (!_isPaused) {
            onResume();
          }
        }
        lastAppState = state;
      }
    }
    
    class ResumeResult {
      dynamic data;
      String source;
    }
    
    @override
      void didPushNext() { //similar to onPause
        // will be called when a new route has been pushed, and the current route is no longer visible. acts similar to onPause
      }
    
      @override
      void didPopNext() { //similar to onResume
         // will be called when the top route has been popped off, and the current route shows up. acts similar to onResume when you are navigated back to your activity/fragment
      }