Created
January 28, 2020 16:04
-
-
Save ryanlid/b26fe9d6695d9b7c602942e404f9954d to your computer and use it in GitHub Desktop.
TabBar选项卡示例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
class TabBarSample extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
// 添加 DefaultTabController 关联 TabBar 及 TabBarView | |
home: DefaultTabController( | |
// 选项卡数量 | |
length: items.length, | |
child: Scaffold( | |
appBar: AppBar( | |
title: const Text('TabBar示例'), | |
bottom: TabBar( | |
// 设置可以滚动 | |
isScrollable: true, | |
// 迭代添加选项卡按钮子项 | |
tabs: items.map((ItemView item) { | |
// 选项卡按钮由文本及图标组成 | |
return Tab( | |
text: item.title, | |
icon: Icon(item.icon), | |
); | |
}).toList(), | |
), | |
), | |
// 添加选项卡视图 | |
body: TabBarView( | |
// 迭代显示选项卡视图 | |
children: items.map((ItemView item) { | |
return Padding( | |
padding: const EdgeInsets.all(16.0), | |
child: SelectedView( | |
item: item, | |
), | |
); | |
}).toList(), | |
), | |
), | |
), | |
); | |
} | |
} | |
// 视图数据 | |
class ItemView { | |
const ItemView({this.title, this.icon}); // 构造方法 | |
// 标题 | |
final String title; | |
// 图标 | |
final IconData icon; | |
} | |
//选项卡的类目 | |
const List<ItemView> items = const <ItemView>[ | |
const ItemView(title: '自驾', icon: Icons.directions_car), | |
const ItemView(title: '自行车', icon: Icons.directions_bike), | |
const ItemView(title: '轮船', icon: Icons.directions_boat), | |
const ItemView(title: '公交车', icon: Icons.directions_bus), | |
const ItemView(title: '火车', icon: Icons.directions_railway), | |
const ItemView(title: '步行', icon: Icons.directions_walk), | |
]; | |
// 被选中的视图 | |
class SelectedView extends StatelessWidget { | |
const SelectedView({Key key, this.item}) : super(key: key); | |
// 视图数据 | |
final ItemView item; | |
@override | |
Widget build(BuildContext context) { | |
// 获取文本主题样式 | |
final TextStyle textStyle = Theme.of(context).textTheme.display1; | |
return Card( | |
color: Colors.white, | |
child: Center( | |
child: Column( | |
mainAxisSize: MainAxisSize.min, | |
crossAxisAlignment: CrossAxisAlignment.center, | |
children: <Widget>[ | |
Icon( | |
item.icon, | |
size: 128.0, | |
color: textStyle.color, | |
), | |
Text( | |
item.title, | |
style: textStyle, | |
) | |
], | |
), | |
), | |
); | |
} | |
} | |
void main() { | |
runApp(TabBarSample()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment