【问题标题】:How to implement a nested TabBarView cleanly/correctly?如何干净/正确地实现嵌套的 TabBarView?
【发布时间】:2018-07-25 15:40:24
【问题描述】:

问题:

我正在尝试实现嵌套的 TabBarView,并成功地这样做了。但是,我不太确定这是编写 Flutter 代码的“干净”方式。

如果我只是将所有小部件放在一个状态类中,一切都会很好。为了更加模块化,我将内部 TabBarView 与外部 TabBarView 分开。但是,我发现 innerTabController 必须驻留在外部 TabBarView 类中,以便内部 TabBarView 正确恢复其先前的索引。

我认为这是糟糕的代码,因为我的外部 TabBarView 需要关注内部 TabBarView 的详细信息(长度、初始索引、...)

class _TestAppState extends State<TestApp>
    with TickerProviderStateMixin {

  TabController _tabController;
  TabController _innerTabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 2,
      vsync: this
    );
    _tabController.addListener(handleTabChange);
    _innerTabController = TabController(
      length: 2,
      vsync: this
    );
  }

问题:

我应该如何构建代码以使其更干净/可维护/模块化? 还是应该使用其他方法来保留内部 TabView 的索引?

代码:

https://gist.github.com/HengJunXi/ae99777df6fc5f902805628b3e270ab4

【问题讨论】:

    标签: flutter


    【解决方案1】:

    我想我已经找到了一种更好的方法来完成这个嵌套标签栏视图的事情,方法是使用 ValueKey 和 PageStorageBucket readState() 和 writeState() 方法。

      final _tabKey = ValueKey('tab');
    
      TabController _innerTabController;
    
      void handleTabChange() {
        print('Inner tab, previous: ${_innerTabController.previousIndex}, current: ${_innerTabController.index}');
        PageStorage.of(context).writeState(context, _innerTabController.index, identifier: _tabKey);
      }
    
      @override
      void initState() {
        super.initState();
        print('init');
        int initialIndex = PageStorage.of(context).readState(context, identifier: _tabKey);
        _innerTabController = TabController(
          length: 2,
          vsync: this,
          initialIndex: initialIndex != null ? initialIndex : 0
        );
        _innerTabController.addListener(handleTabChange);
      }
    

    所有这些代码都将保留在内部选项卡视图类中,因此外部选项卡视图类将不再需要关注内部选项卡。

    完整代码在这里: https://gist.github.com/HengJunXi/b23994fbcb22f0a832dc5c6a50434725

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 2019-12-10
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多