本文实例为大家分享了Flutter实现顶部导航栏的具体代码,供大家参考,具体内容如下
import 'package:flutter/material.dart';
class AppBarDemoPage extends StatelessWidget {
const AppBarDemoPage({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return DefaultTabController(
//导航栏的长度
length: 4,
child: Scaffold(
appBar: AppBar(
title: Text("AppBarDemoPage"),
backgroundColor: Colors.red,
centerTitle: true,
bottom: TabBar(
// isScrollable: true, //可滚动
indicatorColor: Colors.blueGrey, //指示器的颜色
labelColor: Colors.blueGrey, //选中文字颜色
unselectedLabelColor: Colors.white, //为选中文字颜色
// indicatorSize: TabBarIndicatorSize.label, //指示器与文字等宽
tabs: <Widget>[
Tab(text: "热门"),
Tab(text: "推荐"),
Tab(text: "好友"),
Tab(text: "动态"),
],
),
),
body: TabBarView(
children: <Widget>[
Container(
child: Text("hello"),
),
ListView(
children: <Widget>[
ListTile(
title: Text("第二个tab"),
)
],
),
ListView(
children: <Widget>[
ListTile(
title: Text("第三个tab"),
)
],
),
ListView(
children: <Widget>[
ListTile(
title: Text("第四个tab"),
)
],
),
],
),
),
);
}
}
如果底部导航栏和顶部导航栏同时存在的
在这里只写顶部导航栏的实现,底部的可以参照我之前的文章
tabbar导航栏的实现
import 'package:flutter/material.dart';
class CategoryPage extends StatefulWidget {
CategoryPage({Key key}) : super(key: key);
@override
_CategoryPageState createState() => _CategoryPageState();
}
class _CategoryPageState extends State<CategoryPage> {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
title: Row(
children: <Widget>[
Expanded(
child: TabBar(
tabs: <Widget>[
Tab(text: "精选"),
Tab(text: "电影"),
Tab(text: "动漫"),
Tab(text: "NBA"),
],
),
)
],
),
),
body: TabBarView(
children: <Widget>[
ListView(
children: <Widget>[
ListTile(
title: Text("第一个tab"),
)
],
),
ListView(
children: <Widget>[
ListTile(
title: Text("第二个tab"),
)
],
),
ListView(
children: <Widget>[
ListTile(
title: Text("第三个tab"),
)
],
),
ListView(
children: <Widget>[
ListTile(
title: Text("第四个tab"),
)
],
),
],
),
),
);
}
}
这么写是对导航栏点击做的监听,实现效果一样
import 'package:flutter/material.dart';
class NavBarPage extends StatefulWidget {
NavBarPage({Key key}) : super(key: key);
@override
_NavBarPageState createState() => _NavBarPageState();
}
class _NavBarPageState extends State<NavBarPage>
with SingleTickerProviderStateMixin {
TabController _tabController;
@override
void initState() {
super.initState(); //length为导航栏的个数
_tabController = new TabController(vsync: this, length: 2);
_tabController.addListener(() {
print(_tabController.index);//打印点击的索引
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("NavBar"),
bottom: TabBar(
controller: this._tabController,
tabs: <Widget>[
Tab(text: "热销"),
Tab(text: "推荐"),
],
),
),
body: TabBarView(
controller: this._tabController,
children: <Widget>[
Center(child: Text("热销")),
Center(child: Text("推荐"))
],
));
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。