flutter - 在 TabBar 中以编程方式处理 PageViewer 的滑动 - Flutter
问题描述
我已经实现TabBar
了 3 个选项卡。在第二个选项卡中,该类包含PageViewer
及其 3 页。
现在,当我从第一个选项卡滑动到第三个选项卡时,页面出现的顺序是这样的:
1st Tab >>
2nd Tab(PageViewer index 0th page) > (index 1st page) > (index 2nd page) >>
3rd Tab.
但是当我从 3rd Tab 滑动到 1st Tab 时,页面出现的顺序是这样的:
3rd Tab >>
2nd Tab(PageViewer index 0th page) >>
1st Tab.
当我从第三个选项卡转到第一个选项卡时,我想要的是:
3rd Tab >>
2nd Tab(PageViewer index 3rd page) > (index 2nd page) > (index 1st page) >>
1st Tab.
我正在寻找可以有代码示例或手势处理的解决方案。
解决方案
You can keep the track of the previous tab index. Use that to render the pageview's initial page. Refer following code sample.
Tabbar included widget,
class MyTabbedPage extends StatefulWidget {
const MyTabbedPage({Key key}) : super(key: key);
@override
_MyTabbedPageState createState() => _MyTabbedPageState();
}
class _MyTabbedPageState extends State<MyTabbedPage> with SingleTickerProviderStateMixin {
TabController _tabController;
// keeps the track of tab index
int _currentIndex = 0;
@override
void initState() {
super.initState();
_tabController = TabController(vsync: this, length: 3);
_tabController.addListener(_handleTabSelection);
}
_handleTabSelection() {
setState(() {
if (_tabController.index != 1) _currentIndex = _tabController.index;
});
}
@override
void dispose() {
_tabController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
bottom: TabBar(
controller: _tabController,
tabs: [
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
Tab(text: 'Tab 3'),
],
),
title: const Text('Tabs Demo'),
),
body: TabBarView(
controller: _tabController,
children: [
Center(child: Text('Tab 1')),
SecondTab(tabIndex: _currentIndex),
Center(child: Text('Tab 3')),
],
),
),
);
}
}
Pageview included second tab widget,
class SecondTab extends StatelessWidget {
final int tabIndex; // tab index, which came from
SecondTab({Key key, @required this.tabIndex}) : super(key: key);
@override
Widget build(BuildContext context) {
// set initial page to first or last based on previous tab index
final PageController controller = PageController(initialPage: tabIndex);
return PageView(
scrollDirection: Axis.horizontal,
controller: controller,
children: const <Widget>[
Center(child: Text('First Page')),
Center(child: Text('Second Page')),
Center(child: Text('Third Page')),
],
);
}
}
I hope you can get an idea from this.
推荐阅读
- c++ - gtest:使基础测试类成为测试类的朋友
- python - 访问相同代码以获取像素值时出错
- r - Reveal.js 幻灯片在 GitHub 页面上生成 404
- c - 当它应该停止在 0 时,我从 do-while 循环中得到负输出
- python - Azure VM 运行 PowerShell 脚本不输出
- angular - 从服务器返回 Observable 时,Angular TypeScript Date.getFullYear() 不是函数
- sql - 触发器中的 BULK COLLECT
- angular - 导航到其他组件时出现 ObjectUnsuscribedError - Angular
- java - 在 Soap UI 工具中从 putty/Winscp 获取 API 日志
- javascript - 选择某些复选框(单选按钮)时如何启用/禁用 X 输入?