- 在main中的代碼如下
import 'package:flutter/material.dart';
// 底部Tabbar的widget文件引用
import 'Tabbar/buttom_navigator_widget.dart';
void main(List<String> args) {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.red),
title: '底部導(dǎo)航欄切換',
home: BottomNavigationWidget(),
);
}
}
- 創(chuàng)建Tabbar文件夾西设,并創(chuàng)建buttom_navigator_widget文件,使用快捷鍵(stl)創(chuàng)建StatefulWidget代碼“沤欤可以根據(jù)需求創(chuàng)建StatelessWidget 和StatefulWidget不同的widget蛔钙,切換Tabbar時需要保存currentIndex锌云,所以需要創(chuàng)建有狀態(tài)管理的widget,代碼如下:
import 'package:flutter/material.dart';
//個人中心吁脱,記錄儀文件的引用
import 'package:tachograph/page/personal_enter.dart';
import 'package:tachograph/page/recorder.dart';
class BottomNavigationWidget extends StatefulWidget {
const BottomNavigationWidget({Key? key}) : super(key: key);
@override
State<BottomNavigationWidget> createState() => _BottomNavigationWidgetState();
}
class _BottomNavigationWidgetState extends State<BottomNavigationWidget> {
//用于保存點擊的是哪個item
int _currentIndex = 0;
List<Widget> dataList = [];
// 初始化widget數(shù)組桑涎,添加controller
@override
void initState() {
// TODO: implement initState
dataList.add(Recorder());
dataList.add(Personal_center());
super.initState();
}
@override
Widget build(BuildContext context) {
// 腳手架widget,
return Scaffold(
body: dataList[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
unselectedItemColor: Colors.red, //未選中顏色
selectedItemColor: Colors.green, // 選中顏色
items: [
BottomNavigationBarItem(
icon: Icon(
Icons.home,
color: Colors.blue,
),
title: Text(
'記錄儀',
// style: TextStyle(color: Colors.redAccent),
)),
BottomNavigationBarItem(
icon: Icon(
Icons.mail,
// color: Colors.red,
),
title: Text(
'個人中心',
// style: TextStyle(color: Colors.redAccent),
)),
],
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed,
// item 點擊處理
onTap: (int value) {
setState(() {
_currentIndex = value;
});
},
),
);
}
}
- 創(chuàng)建page文件夾兼贡,并創(chuàng)建Personal_center和Recorder文件攻冷,代碼如下:
import 'package:flutter/material.dart';
class Personal_center extends StatelessWidget {
const Personal_center({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(
"個人中心",
style: TextStyle(color: Colors.red, fontSize: 20),
),
),
);
}
}
import 'package:flutter/material.dart';
class Recorder extends StatelessWidget {
const Recorder({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(
'記錄儀',
style: TextStyle(color: Colors.green, fontSize: 20),
),
),
);
}
}
-
運行代碼,效果如下:
Simulator Screen Shot - iPhone 8 - 2022-04-16 at 11.35.24.png
Simulator Screen Shot - iPhone 8 - 2022-04-16 at 11.35.28.png