重建父级时调用子级 init 方法 - flutter

ujj*_*ali 5 dart hybrid-mobile-app flutter

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

 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),
Run Code Online (Sandbox Code Playgroud)

这里的 _currentActiveIndex 是类的状态之一,其中根据 _currentActiveIndex 的值呈现单独的主体小部件。

 body: TabBarView(children: <Widget>[
      new PostLoadWidget.express(),
      new PostLoadWidget.confess(),
    ]),
Run Code Online (Sandbox Code Playgroud)

这是脚手架小部件的主体:- 基于上面的 _currentActiveIndex 呈现的小部件。

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

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

die*_*per 3

您可以使用 mixinAutomaticKeepAliveClientMixin并覆盖wantKeepAlivegetter 并返回 true 以避免每次都重新创建 State。

        class PostLoadWidgetState extends State<PostLoadWidget> with AutomaticKeepAliveClientMixin<PostLoadWidget> {


            ...

            @override
            bool get wantKeepAlive => true;

        }
Run Code Online (Sandbox Code Playgroud)

更多信息请参见:https://medium.com/@diegovoper/flutter-persistent-tab-bars-a26220d322bc

  • 我已经尝试过使用AutomaticKeepAliveClient mixin,并根据文档在wantKeepAlive上返回true,这是状态的默认行为,这并不能解决我的问题。 (3认同)