Tab开关上多次调用函数initState()

时间:2019-03-09 17:33:49

标签: flutter

所有选项卡都是StatefulWidgets,并且扩展了AbstractTimelineState.class,后者扩展了State.class。问题是在切换选项卡时,函数fetchTimeline()(在initState()内部)被多次调用-上一个选项卡和新激活的选项卡中再次调用。有时这会导致fetchTimeline()的内容显示在错误的Tab上,具体取决于哪个Tab的fetchTimeline()调用首先返回(请参见AbstractTimelineState build()中的StreamBuilder函数)

fetchTimeline函数仅应调用一次(对于新激活的Tab)。

//Each Tab uses AbstractTimelineState as State


class TimelineSubTab extends StatefulWidget {
  final MainBloc _mainBloc;

  TimelineSubTab(this._mainBloc,{Key key}) :super(key: key);

  _TimelineSubTabState createState() => _TimelineSubTabState(_mainBloc);
}

class _TimelineSubTabState extends AbstractTimelineState<TimelineSubTab>{
  final MainBloc _mainBloc;
  _TimelineSubTabState(this._mainBloc):super(_mainBloc);

  fetchTimeline(int maxId, int sinceId){
    _mainBloc.fetchTimeline(maxId, sinceId);
  }
}


//abstract state class

abstract class AbstractTimelineState<T extends StatefulWidget> extends State<T>{
  fetchTimeline(int maxId, int sinceId); //<-- abstract method

  MainBloc _mainBloc;

AbstractTimelineState(this._mainBloc);

  @override
  void initState() {
    super.initState();
    fetchTimeline(0, 0); //called multiple times on Tab switch.
    ...
  }


  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
    stream: _mainBloc.getTimeline,
    initialData: null,
    builder: (BuildContext context, AsyncSnapshot snapshot) 
    {..}
  }
  }

0 个答案:

没有答案