问题描述
我有一个带状态的窗口小部件,顶部带有标签,下面有一个列表.该列表分为不同的类别.每个类别都列在每个选项卡中.我要做的是在选项卡中按下某个项目时,我希望列表中的相应类别滚动查看.
I have a stateful widget with tabs at the top and has a list below it. The list is subdivided into different categories. Each category is listed into each tab. What I want to do is when an item is pressed in the tab, I want its corresponding category in the list to scroll to view.
以下是相关代码供参考:
Here is the relevant code for reference:
SliverPersistentHeader(
pinned: true,
delegate: _SliverAppBarTabDelegate(
child: Container(
child: TabBar(
isScrollable: true,
labelColor: Colors.black,
tabs: createTabList(),
controller: tabBarController,
),
),
),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
return Padding(
padding: const EdgeInsets.only(top: kSpacerRegular),
child: RestaurantMenuCard(menuCard: menuCards[index]),
);
},
childCount: menuCards.length,
),
),
我整天都在寻找解决方案,但找不到解决方案.我也尝试过此程序包,但似乎不适用于我的情况.
I searched all day looking for a solution but could not find one. I also tried this package but does not seem to work in my case.
这是我的小工具树",用于更多上下文:
Here is my 'widget tree' for more context:
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(),
SliverPersistentHeader(),
SliverList(),
],
),
);
}
添加了更多上下文的屏幕截图
Added a screen capture for more context
推荐答案
我借助此.我用SliverToBoxAdapter
替换了SliverList
.子是Column
中我的RestaurantMenuCard
的列表.因此,生成的小部件树为:
I solved the issue with the help of this answer. I replaced SliverList
with SliverToBoxAdapter
. The child is the list of my RestaurantMenuCard
in a Column
. Thus, the resulting widget tree is:
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(),
SliverPersistentHeader(),
SliverToBoxAdapter(
Column(
RestaurantMenuCard(),
RestaurantMenuCard(),
...
),
),
],
),
);
}
如链接答案中所述,当我向RestaurantMenuCard
的每个实例添加全局密钥时,魔术就发生了.
The magic happens when I added a global key to each instance of the RestaurantMenuCard
as discussed in the linked answer.
最后,我在TabBar
的onTap
函数中触发了Scrollable.ensureVisible(context)
.
Then finally, I trigger the Scrollable.ensureVisible(context)
in onTap
function of my TabBar
.
这篇关于Flutter:按下Tab时自动滚动到SliverList项之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!