当前位置:   article > 正文

Flutter TabController DefaultTabController 中添加监听器?

defaulttabcontroller

  1. import 'package:flutter/material.dart';
  2. class SettingsPage extends StatefulWidget {
  3. SettingsPage({Key key}) : super(key: key);
  4. @override
  5. _SettingsPageState createState() => _SettingsPageState();
  6. }
  7. // 1 实现 SingleTickerProviderStateMixin
  8. class _SettingsPageState extends State<SettingsPage>
  9. with SingleTickerProviderStateMixin {
  10. // 2 定义 TabController 变量
  11. TabController _tabController;
  12. // 3 覆盖重写 initState,实例化 _tabController
  13. @override
  14. void initState() {
  15. // TODO: implement initState
  16. super.initState();
  17. _tabController = new TabController(length: 2, vsync: SettingsPage());
  18. _tabController.addListener(() {
  19. print(_tabController.index);
  20. });
  21. }
  22. @override
  23. Widget build(BuildContext context) {
  24. return Scaffold(
  25. appBar: AppBar(
  26. title: Text('tabController'),
  27. bottom: TabBar(
  28. controller: _tabController, // 4 需要配置 controller!!!
  29. // isScrollable: true,
  30. tabs: <Widget>[
  31. Tab(text: '推荐'),
  32. Tab(text: '最新'),
  33. ],
  34. ),
  35. ),
  36. body: TabBarView(
  37. controller: _tabController, // 4 需要配置 controller!!!
  38. children: <Widget>[
  39. ListView(
  40. children: <Widget>[
  41. ListTile(
  42. title: Text(
  43. 'diyigezuixin 推荐',
  44. style: TextStyle(fontSize: 14.0),
  45. ),
  46. ),
  47. ListTile(
  48. title: Text('diyigezuixin 推荐'),
  49. ),
  50. ],
  51. ),
  52. Container(
  53. child: Text('zuixidddd'),
  54. ),
  55. ],
  56. ),
  57. );
  58. }
  59. }

  1. new DefaultTabController(
  2. child: Builder(
  3. builder: (context) {
  4. final tabController = DefaultTabController.of(context)!;
  5. tabController.addListener(() {
  6. print("New tab index: ${tabController.index}");
  7. });
  8. return Scaffold(
  9. ...
  10. );
  11. }
  12. ),
  13. );

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/431990
推荐阅读
相关标签
  

闽ICP备14008679号