【问题标题】:Scroll Controller synchronized with Tabs in flutter滚动控制器与颤动中的选项卡同步
【发布时间】:2020-08-28 07:40:03
【问题描述】:

我有一个滚动控制器来管理我的 gridview 的滚动功能,但在 gridview 上方我有一个标签栏,当按下每个标签时,它会将页面滚动到 gridview 中的不同位置。如下面的代码所示。但是当我滚动浏览 gridview 本身时,选项卡不会更改它们的选择。我需要知道如何实现这一点,类似于:

https://www.youtube.com/watch?v=LrOR5QOCHBI

    Future<void> _scrollControllerAnimation(double offset) {
      return _scrollController.animateTo(
        offset,
        duration: Duration(milliseconds: 500),
        curve: Curves.easeIn,
      );
    }

TabBar(
                  controller: _tabController,
                  isScrollable: true,
                  labelColor: Colors.black,
                  unselectedLabelColor: Colors.black.withOpacity(0.3),

                  onTap: (int){

                    switch (int) {

                      case 0: _scrollControllerAnimation(0);break;
                      case 1: _scrollControllerAnimation(70);break;
                      case 2: _scrollControllerAnimation(140);break;
                      case 3: _scrollControllerAnimation(210);break;
                      case 4: _scrollControllerAnimation(280);break;
                      case 5: _scrollControllerAnimation(350);break;
                      case 6: _scrollControllerAnimation(420);break;
                      case 7: _scrollControllerAnimation(490);break;
                      case 8: _scrollControllerAnimation(560);break;
                      case 9: _scrollControllerAnimation(630);break;
                      case 10: _scrollControllerAnimation(700);break;
                      case 11: _scrollControllerAnimation(770);break;

                      default: _scrollControllerAnimation(0);
                    }
                  },

                  tabs: choices.map((Choice choice) {
                      return Tab(
                      text: choice.title,
                    );
                  }).toList(),
                ),

【问题讨论】:

  • 您是否偶然找到了解决方案?请分享它,我需要实现完全相同的东西。

标签: flutter dart


【解决方案1】:

您可以通过向滚动控制器添加侦听器来实现此目的,并且在侦听器中,根据滚动控制器的偏移量,您可以在 tabController 上调用 animateTo。您可以实例化控制器并在 initState 中附加侦听器,因为它在小部件的生命周期中只被调用一次。

可能看起来像这样:

@override
void initState() {
  _scrollController = ScrollController();
  _tabController = TabController(vsync: this, length: 8);

  _scrollController.addListener(() {
    int tabIndex = _tabController.index;
    int targetIndex = _targetIndex(_scrollController.offset);
    if (targetIndex != tabIndex) {
      _tabController.animateTo(
        targetIndex,
        duration: Duration(milliseconds: 400),
      );
    }
  });
  super.initState();
}

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 2023-02-06
    • 2020-04-16
    • 2021-09-07
    • 2011-06-22
    • 2020-12-10
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多