【问题标题】:child init method is called when parent is rebuild - flutter重建父级时调用子级初始化方法 - 颤动
【发布时间】:2019-04-07 15:22:32
【问题描述】:

据我了解和颤振的工作机制,有状态的小部件方法仅在其第一次在小部件树中构建时调用一次,并且每次更改其状态或重建父级时调用构建方法方法。

 bottomNavigationBar: BottomNavigationBar(items: [
      BottomNavigationBarItem(icon: new Icon(Icons.home,), title: new Text("HOME", style: new TextStyle(fontSize: 11.0),),),
      BottomNavigationBarItem(icon: new Icon(Icons.message,), title: new Text("MESSAGES", style: new TextStyle(fontSize: 11.0),),),
      BottomNavigationBarItem(icon: new Icon(Icons.notifications,), title: new Text("NOTIFICATIONS", style: new TextStyle(fontSize: 11.0),),),
      BottomNavigationBarItem(icon: new Icon(Icons.assignment,), title: new Text("MENTOR", style: new TextStyle(fontSize: 11.0),),),
      BottomNavigationBarItem(icon: new Icon(Icons.account_circle,), title: new Text("PROFILE", style: new TextStyle(fontSize: 11.0),),),
    ],
      onTap: (int index){
        setState(() {
          _currentActiveIndex = index;
        });
      },
      currentIndex: _currentActiveIndex,
      type: BottomNavigationBarType.shifting,
    ),
    body: _getCurrentPage(_currentActiveIndex),

这里的_currentActiveIndex是一个类的状态之一,根据_currentActiveIndex的值呈现一个单独的body widget。

 body: TabBarView(children: <Widget>[
      new PostLoadWidget.express(),
      new PostLoadWidget.confess(),
    ]),

这是脚手架小部件的主体:- 根据上面的 _currentActiveIndex 渲染的小部件。

class PostLoadWidgetState extends State<PostLoadWidget> {
   @override
   void initState(){
       print("initState is called here);
       super.initState();
    }
}

每次重建父母时(上图),在 _curentActiveIndex 发生更改的地方,都会调用 PostLoadWidgetState initState() 方法,这是所需的行为。我一直在 initState() 中初始化网络调用,我不想在每次重建其父级时都调用它。

【问题讨论】:

    标签: dart flutter hybrid-mobile-app


    【解决方案1】:

    您可以使用 mixin AutomaticKeepAliveClientMixin 并覆盖 wantKeepAlive getter 并返回 true 以避免每次都重新创建 State。

            class PostLoadWidgetState extends State<PostLoadWidget> with AutomaticKeepAliveClientMixin<PostLoadWidget> {
    
    
                ...
    
                @override
                bool get wantKeepAlive => true;
    
            }
    

    更多信息在这里:https://medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc

    【讨论】:

    • 我已经尝试过 AutomaticKeepAliveClient mixin 并根据文档在 wantKeepAlive 上返回 true,这是状态的默认行为,这并不能解决我的问题。
    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 2015-07-28
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    相关资源
    最近更新 更多