在颤动中,实现选项卡布局既简单又直接。这是官方文档中的一个简单示例:
import 'package:flutter/material.dart'; void main() { runApp(new TabBarDemo()); } class TabBarDemo extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new DefaultTabController( length: 3, child: new Scaffold( appBar: new AppBar( bottom: new TabBar( tabs: [ new Tab(icon: new Icon(Icons.directions_car)), new Tab(icon: new Icon(Icons.directions_transit)), new Tab(icon: new Icon(Icons.directions_bike)), ], ), title: new Text('Tabs Demo'), ), body: new TabBarView( children: [ new Icon(Icons.directions_car), new Icon(Icons.directions_transit), new Icon(Icons.directions_bike), ], ), ), ), ); } }
但是,我要获取活动的标签索引,以便可以在某些标签上应用一些逻辑。我搜索了文档,但无法弄清楚。你们可以帮助和感谢吗?
重点DefaultTabController在于它可以自行管理标签。
DefaultTabController
如果要进行一些自定义标签管理,请TabController改用。有了TabController你有机会获得更多的信息,包括当前的索引。
TabController
class MyTabbedPage extends StatefulWidget { const MyTabbedPage({Key key}) : super(key: key); @override _MyTabbedPageState createState() => new _MyTabbedPageState(); } class _MyTabbedPageState extends State<MyTabbedPage> with SingleTickerProviderStateMixin { final List<Tab> myTabs = <Tab>[ new Tab(text: 'LEFT'), new Tab(text: 'RIGHT'), ]; TabController _tabController; @override void initState() { super.initState(); _tabController = new TabController(vsync: this, length: myTabs.length); } @override void dispose() { _tabController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( bottom: new TabBar( controller: _tabController, tabs: myTabs, ), ), body: new TabBarView( controller: _tabController, children: myTabs.map((Tab tab) { return new Center(child: new Text(tab.text)); }).toList(), ), ); } }