前言
Flutter相對(duì)OC來(lái)說(shuō),代碼精簡(jiǎn)很多,目標(biāo)文件也少了很多蒋川,下面我們通過(guò)代碼一一講解如何利用flutter去搭建一個(gè)App的基礎(chǔ)殼子,核心需要理解和注意的有MaterialApp()
撩笆、Scaffold()
尔破、appBar: AppBar( )
、Column
浇衬、Row
懒构、bottomNavigationBar
等核心組件。具體用法和介紹看下列代碼和注釋耘擂。
import 'package:flutter/material.dart'; // 導(dǎo)入文件樣式
import './widgets/tabBar_widget.dart'; // 導(dǎo)入自定義文件
// main函數(shù)和OC一樣胆剧,都是程序的入口
void main() => runApp(ShopkeeperApp()); // 如果函數(shù)中只有一行方法的調(diào)用,可以去掉{}用=>指向即可
class ShopkeeperApp extends StatelessWidget { //
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false, // DEBUG條幅隱藏
home: Home(), // 首頁(yè)顯示內(nèi)容
// 設(shè)置主題顏色
theme: ThemeData(
// 導(dǎo)航條顏色
primaryColor: Colors.cyan,
// 設(shè)置按鈕點(diǎn)擊時(shí)的水波紋
highlightColor:
Color.fromRGBO(255, 255, 255, 0.5), //設(shè)置點(diǎn)擊時(shí)的背景色為白色,透明度為0.5
splashColor: Colors.white70, // 點(diǎn)擊按鈕時(shí)的水波紋顏色為白色不透明
),
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DefaultTabController( // 相當(dāng)于OC中baseController
length: 4, // 設(shè)置4個(gè)根控制器
child: Scaffold(
appBar: AppBar( // 設(shè)置導(dǎo)航條
title: Text( // 導(dǎo)航條標(biāo)題
'智掌柜',
style: TextStyle( // 文案樣式
color: Colors.white,
fontSize: 18.0
),
),
),
// body: TabBarView(children: [
//
// ]),
body: Center( // body是整個(gè)控制器中要顯示的內(nèi)容
child: Column( // Column是縱向顯示 Row是橫向顯示
children: [
Text("這個(gè)是字符串標(biāo)簽秩霍,相當(dāng)于OC中的Label"),
SizedBox(
height: 10,
),
Text("這個(gè)是字符串標(biāo)簽篙悯,相當(dāng)于OC中的Label"),
SizedBox(
height: 10,
),
Text("這個(gè)是字符串標(biāo)簽,相當(dāng)于OC中的Label"),
],
),
),
bottomNavigationBar: setBottomNavigationBar(), // 設(shè)置tabBar樣式
),
);
}
}
- 其中
setBottomNavigationBar()
函數(shù)是自定義文件中的方法铃绒,內(nèi)容就是設(shè)置底部餐單欄的樣式和內(nèi)容鸽照。具體查看下來(lái)代碼。
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
// 這里要注意下StatefulWidget合StatelessWidget的寫(xiě)法
class setBottomNavigationBar extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _createBottomNavigationBarItem();
}
}
// _開(kāi)頭的就是私有方法
class _createBottomNavigationBarItem extends State<setBottomNavigationBar> {
int _CurrentIndex = 0; // 默認(rèn)選中第0個(gè)控制器
void _onTapHandle(int index) { // 點(diǎn)擊對(duì)應(yīng)的index
setState(() {
print('您點(diǎn)擊的是:{$index}'); // flutter的打印方式
_CurrentIndex = index; // 點(diǎn)擊后的賦值
});
}
@override
Widget build(BuildContext context) {
return BottomNavigationBar( // BottomNavigationBar就是底部菜單欄的樣式組件
currentIndex: _CurrentIndex, // 當(dāng)前顯示的索引
onTap: _onTapHandle,// onTapitem的電機(jī)事件
type: BottomNavigationBarType.fixed, // type表示固定顯示在底部
items: [ // 設(shè)置tabBar的item
BottomNavigationBarItem(icon: Icon(Icons.explore),label: 'Explore'),// BottomNavigationBarItem 具體的某個(gè)item的設(shè)置
BottomNavigationBarItem(icon: Icon(Icons.history),label: 'History'),
BottomNavigationBarItem(icon: Icon(Icons.list),label: 'List'),
BottomNavigationBarItem(icon: Icon(Icons.person),label: 'Persion'),
],
);
}
}
導(dǎo)航條+底部tabBar+控制器