作者:无声无息无心跳 | 来源:互联网 | 2023-08-26 18:00
效果图:
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() {
super.dispose();
_tabController.dispose();
}
@override
void 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,
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(),
'/appBarDemo':(context)=>AppBarDemoPage(),
'/tabBarController':(context)=>TabBarControllerPage()
};
var oonGenerateRoute=(RouteSettings settings) {
final String name = settings.name;
final Function pageContentBuilder = routes[name];
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;
}
}
};