[英]How to make the selected Tab center in TabBar in flutter
In my TabBar, there are up to 3 kinds of tabs of different widths.在我的 TabBar 中,最多有 3 种不同宽度的选项卡。
"x月xx" has the widest width, "xx月" is the middle, "x月" has the narrowest width. “x月xx”最宽,“xx月”在中间,“x月”最窄。
And when the tab state change from unselected to selected, it will become more wide because it add the prefix "xxxx年" to the title.而当标签 state 从未选中变为选中时,它会变得更宽,因为它在标题中添加了前缀“xxxx年”。
I can not set a specific value to tab width, because the tab title may change from "2020年11月" to "11月" if unselected.我无法为选项卡宽度设置特定值,因为如果未选中,选项卡标题可能会从“2020 年 11 月”更改为“11 月”。
My purpose is to center the selected tab on the screen.我的目的是使选定的选项卡在屏幕上居中。
The method animateTo
of TabController
only allows scrolling to an index but not a distance. TabController
的方法animateTo
只允许滚动到一个索引而不是一个距离。 So I copied the tabs.dart
.所以我复制了
tabs.dart
。 I want to change the method _scrollToCurrentIndex()
which uses a ScrollController
to animate to an offset.我想更改
_scrollToCurrentIndex()
方法,它使用ScrollController
将动画设置为偏移量。 There are many things(eg various TabOffsets, ScrollOffset, viewportWidth...) useful, but I still don' t know how to let scroll offset and padding work together.有很多有用的东西(例如各种 TabOffsets、ScrollOffset、viewportWidth...),但我仍然不知道如何让滚动偏移和填充一起工作。
I succeeded partly, that means, the selected tab will scroll to center, but the animation is strange.我部分成功了,这意味着选定的选项卡将滚动到中心,但 animation 很奇怪。
In class _TabBarState extends State<TabBar>
I found this in build function:在
class _TabBarState extends State<TabBar>
我在构建 function 中找到了这个:
Widget tabBar = CustomPaint(
painter: _indicatorPainter,
child: _TabStyle(
// ...
child: _TabLabelBar(
onPerformLayout: _saveTabOffsets,
children: wrappedTabs,
),
),
);
In onPerformLayout: _saveTabOffsets
I can get List<double> tabOffsets
and double tabBarWidth
.在
onPerformLayout: _saveTabOffsets
我可以得到List<double> tabOffsets
和double tabBarWidth
。 I use these to calculate the distance to scroll.我用这些来计算滚动的距离。 But in this way, the problem is: when click a tab, it draws the indicator first, and after the indicator change from the last selected tab to the new selected tab, the tabBar scrolls to center it.
但是这样一来,问题就在于:当点击一个tab时,它先绘制indicator,然后indicator从最后一个选中的tab变为新选中的tab后,tabBar滚动到居中。
I am open to better ideas.我愿意接受更好的想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.