赞
踩
效果图:
Home.dart
TabBarController.dart
Home.dart
import 'package:flutter/material.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RaisedButton( child: Text('跳转到appBar'), onPressed: (){ //路由跳转 Navigator.pushNamed(context, '/appBarDemo'); }, ), SizedBox(width: 10,), RaisedButton( child: Text('TabController定义顶部tab切换 '), onPressed: (){ //路由跳转 Navigator.pushNamed(context, '/tabBarController'); }, ) ], ), ); } }
TabBarController.dart
import 'package:flutter/material.dart'; class TabBarControllerPage extends StatefulWidget { @override _TabBarControllerPageState createState() => _TabBarControllerPageState(); } class _TabBarControllerPageState extends State<TabBarControllerPage> with SingleTickerProviderStateMixin { TabController _tabController; //第二种配置顶部导航的方式、 @override void dispose() { //声明周期函数,销毁时调用 // TODO: implement dispose super.dispose(); _tabController.dispose(); //销毁时,把_tabController也给销毁 } @override void initState() { //生命周期函数,初始化时,自动调用 // TODO: implement initState super.initState(); _tabController=new TabController(length: 2, vsync: this); //调用构造方法初始化时,进行实例化,参数一是长度,参数二是固定写法 _tabController.addListener((){ print(_tabController.index); //监听改变时的下标 }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('TabBarControllerpage'), bottom: TabBar( controller: this._tabController, //注意,这里是不一样的地方,要让controller=上面的_tabController tabs: <Widget>[ Tab(text:"热销"), Tab(text:"推荐"), ], ), ), body: TabBarView( controller: this._tabController, //注意这里也需要配置 children: <Widget>[ Center(child: Text('热销'),), Center(child: Text('推荐'),), ], ), ); } }
还有记得配置命名路由哟:
Routes.dart
import '../pages/Tabs.dart'; import 'package:flutter/material.dart'; import '../pages/AppBarDemo.dart'; import '../pages/TabBarController.dart'; //配置路由 final routes={ //配置命名路由 '/':(context)=>Tabs(), //命名路由传值 arguments工具是必须的 '/appBarDemo':(context)=>AppBarDemoPage(), '/tabBarController':(context)=>TabBarControllerPage() }; //固定写法 var oonGenerateRoute=(RouteSettings settings) { // 统一处理 final String name = settings.name; //得到命名路由的名字,例如:'/form' final Function pageContentBuilder = routes[name]; //得到命名路由的键去获取值,例如:(context)=>FormPage(), if (pageContentBuilder != null) { if (settings.arguments != null) { final Route route = MaterialPageRoute( builder: (context) => pageContentBuilder(context, arguments: settings.arguments)); return route; } else { final Route route = MaterialPageRoute( builder: (context) => pageContentBuilder(context)); return route; } } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。