必须使用TabController。没有在TabController中使用 TabBard的报错
简单的选项卡
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MyTabPage();
}
}
class MyTabPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new MyTabPageState();
}
}
class MyTabPageState extends State<MyTabPage> {
List<Tab> tab = <Tab>[
Tab(
text: "选项卡1",
),
Tab(
text: "选项卡2",
)
];
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "tabTar示例",
home: new DefaultTabController(
length: 2,
child: new Scaffold(
appBar: new AppBar(
bottom: new TabBar(tabs: tab),
),
body: new TabBarView(
//迭代
children: tab.map((Tab tab) {
return Center(
child: new Text("内容:"+tab.text),
);
}).toList()),
),
),
);
}
}
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "tab示例二",
home: new DefaultTabController(
//tab的数量 该字段必须有
length: items.length,
child: new Scaffold(
appBar: new AppBar(
bottom: new TabBar(
//迭代items 并生成Tab对象
tabs: items.map((ItemView item) {
return new Tab(
text: item.title,
icon: new Icon(item.icon),
);
}).toList(),
//是否可以滚动
isScrollable: true,
),
),
body: new TabBarView(
children: items.map((ItemView item) {
return new Padding(
padding: EdgeInsets.all(16),
child: new Center(child: new SelectView(itemView: item)),
);
}).toList()),
)));
}
}
//tab 图标的集合
const List<ItemView> items = const <ItemView>[
ItemView(title: "自驾", icon: Icons.directions_car),
ItemView(title: "自行车", icon: Icons.directions_bike),
ItemView(title: "自驾3", icon: Icons.directions_car),
ItemView(title: "自驾4", icon: Icons.directions_car),
ItemView(title: "自驾5", icon: Icons.directions_car),
ItemView(title: "自驾6", icon: Icons.directions_car),
];
//自定义类型 itemTab
class ItemView {
const ItemView({this.title, this.icon});
final String title;
final IconData icon;
}
class SelectView extends StatelessWidget {
final ItemView itemView;
const SelectView({Key key, this.itemView}) : super(key: key);
// const SelectView({ Key key, this.itemView }) : super(key: key);
@override
Widget build(BuildContext context) {
final TextStyle textStyle = Theme.of(context).textTheme.display1;
return new Card(
color: Colors.white,
child: new Center(
child: new Column(
mainAxisSize: MainAxisSize.min, //垂直方向最小化处理
crossAxisAlignment: CrossAxisAlignment.center, //水平反向居中对齐
children: <Widget>[
new Text(itemView.title),
new Icon(itemView.icon, size: 128, color: textStyle.color)
],
),
),
);
}
}
参考:Flutter 技术入门与实战