дочерний метод init вызывается при перестроении parent - flutter - PullRequest
0 голосов
/ 03 ноября 2018

Насколько я понимаю, и рабочий механизм трепетания, метод виджета с сохранением состояния вызывается только один раз, когда его первая сборка в дереве виджетов и метод метода вызова вызываются каждый раз, когда изменяется его состояние или перестраивается родитель.

 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: 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 (), который я не хочу вызывать при каждой перестройке его родителей.

1 Ответ

0 голосов
/ 04 ноября 2018

Вы можете использовать миксин AutomaticKeepAliveClientMixin и переопределить метод получения wantKeepAlive и вернуть true, чтобы избежать повторного создания состояния каждый раз.

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


            ...

            @override
            bool get wantKeepAlive => true;

        }

Подробнее здесь: https://medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc

...