您的位置:首页 > 其它

flutter通过底部导航栏实现不同page之间的切换:

2019-04-23 15:36 1091 查看

实现逻辑上flutter显得更加紧凑,而在android开发中同样的实现结果需要通过不同的结构组合(例如创建不同布局的xml,设置adapter,之后将adapter设置给指定的控件)。
而在flutter中可以直接通过对不同widget设置指定的事件更加降低了代码的耦合性。
如下为flutter创建导航栏切换的实例:
1 创建Pagerview并添加不同的页面;

body: PageView(
//pageview
controller: _controller,
children: <Widget>[
//添加需要显示的页面
MyPage(),
HomePage(),
SearchPage(),
TravelPage(),
],
),

2 scaffold中添加底部导航栏并给每个导航栏添加点击切换。
(添加点击事件的核心代码)

currentIndex: _currentIndex, //当下点击的条目
onTap: (index) {  //点击事件  在点击到指定的图标  改变currentindex
_controller.jumpToPage(index);
setState(() {
_currentIndex = index;
});
},

总代码如下(另需单独创建不同的显示页面):

import 'package:flutter/material.dart';
import 'package:photo_test/Pages/MyPage.dart';
import 'package:photo_test/Pages/SearchPage.dart';
import 'package:photo_test/Pages/TravelPage.dart';
import 'package:photo_test/Pages/homePage.dart';

//底部导航栏实现不同page的切换
class TabNavigator extends StatefulWidget {
@override
_TabNavigatorState createState() {
return _TabNavigatorState();
}
}

class _TabNavigatorState extends State<TabNavigator> {
//定义默认状态和点击状态的颜色
Color _defaultColor = Colors.blueGrey;
Color _activeColor = Colors.red;
int _currentIndex = 0;

//定义一个pagecontroller 用于控制指定页面的显示
final PageController _controller = PageController(
initialPage: 0,
);

@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
//pageview
controller: _controller,
children: <Widget>[
//添加需要显示的页面
MyPage(),
HomePage(),
SearchPage(),
TravelPage(),
],
),
bottomNavigationBar: BottomNavigationBar(
//添加底部导航栏
currentIndex: _currentIndex, //当下点击的条目
onTap: (index) {  //点击事件  在点击到指定的图标  改变currentindex
_controller.jumpToPage(index);
setState(() {
_currentIndex = index;
});
},type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home, color: _defaultColor),
activeIcon: Icon(Icons.home, color: _activeColor),
title: Text(
'首页',
style: TextStyle(
color: _currentIndex != 0 ? _defaultColor : _activeColor),
),
),
BottomNavigationBarItem(
icon: Icon(Icons.search, color: _defaultColor),
activeIcon: Icon(Icons.search, color: _activeColor),
title: Text(
'搜索',
style: TextStyle(
color: _currentIndex != 1 ? _defaultColor : _activeColor),
),
),
BottomNavigationBarItem(
icon: Icon(Icons.camera_alt, color: _defaultColor),
activeIcon: Icon(Icons.camera_alt, color: _activeColor),
title: Text(
'旅拍',
style: TextStyle(
color: _currentIndex != 2 ? _defaultColor : _activeColor),
),
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle, color: _defaultColor),
activeIcon: Icon(Icons.account_circle, color: _activeColor),
title: Text(
'我的',
style: TextStyle(
color: _currentIndex != 3 ? _defaultColor : _activeColor),
),
),
]),
);
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: