我面临标签栏的问题。实际上,我的应用程序中有四个选项卡(即四个类别)。有一个单独的块根据类别 ID 从存储库中获取数据。所以我添加了一个_tabController.addListener(_onTabChanged);属性,并根据当前选项卡(即当前类别)调用 bloc 事件。但问题是 addListener 在到达该选项卡时执行该行,而不是在通过前一个动画到下一个动画时执行该行。因此,这会在下一个选项卡上显示上一个选项卡的内容一秒钟,然后重新加载其所需的内容,这很烦人。所以我的问题是,有没有一种方法可以在动画期间从一个选项卡到另一个选项卡而不到达那里请求具有所需类别 ID 的集团?
这是代码:
class CategoryTab extends StatefulWidget {
final List<Category> categories;
const CategoryTab({Key key, this.categories}) : super(key: key);
@override
_CategoryTabState createState() => _CategoryTabState();
}
class _CategoryTabState extends State<CategoryTab>
with SingleTickerProviderStateMixin {
TabController _tabController;
int activeTab;
@override
void initState() {
super.initState();
activeTab = 0;
_tabController = TabController(
vsync: this, length: widget.categories.length, initialIndex: activeTab);
_tabController.addListener(_onTabChanged);
context.read<SoundBloc>().add(GetSounds(categoryId: '1'));
print(_tabController.index);
}
void _onTabChanged() {
if (!_tabController.indexIsChanging && activeTab != _tabController.index) {
activeTab = _tabController.index;
context
.read<SoundBloc>()
.add(GetSounds(categoryId: (activeTab + 1).toString()));
}
}
@override
void dispose() {
_tabController.removeListener(_onTabChanged);
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text(
'Sounds',
style: Theme.of(context).textTheme.headline5,
),
bottom: TabBar(
controller: _tabController,
isScrollable: true,
indicator: CustomTabIndicator(),
physics: BouncingScrollPhysics(),
unselectedLabelColor: Colors.redAccent,
indicatorSize: TabBarIndicatorSize.tab,
tabs: widget.categories
.map((category) => CatgoryTabItemWidget(category: category))
.toList(),
),
),
body: TabBarView(
controller: _tabController,
children: widget.categories
.map((category) => SoundView(
category: category,
))
.toList(),
),
),
);
}
}
注意类别 id 从 1 开始,即 1、2、3、4(4 个类别)。