App端主要的就是UI的搭建跳芳,和數(shù)據(jù)的請求菊碟,然后將服務端的數(shù)據(jù)以精美的UI展示出來缠俺,通過這種方法將信息傳遞給普通用戶。普通用戶在App上進行操作踩寇,將用戶行為和數(shù)據(jù)上傳到服務端啄清。所以當我們剛開始接觸Flutter這一跨平臺開發(fā)的時候首先可以先了解一下我們的Flutter UI的搭建。
為什么要學習Flutter俺孙?
why.jpg
Flutter是Google的開源UI框架,F(xiàn)lutter生成的程序可以直接在Google最新的系統(tǒng)Fuschia
上運行掷贾, 也可以build成apk
在android
上運行睛榄,或是生成ipa
在iOS
運行。
一般傳統(tǒng)的跨平臺解決方案如RN想帅,Weex等都是將程序員編寫的代碼自動轉換成Native代碼场靴,最終渲染工作交還給系統(tǒng),使用類HTML+JS的UI構建邏輯港准,但是最終會生成對應的自定義原生控件旨剥。
Flutter重寫了一套跨平臺的UI框架。渲染引擎依靠跨平臺的Skia圖形庫來自己繪制浅缸。邏輯處理使用支持AOT的Dart語言轨帜,執(zhí)行效率也比JS高很多。
- 一. FlutterUI整體架構
跨平臺應用的框架衩椒,沒有使用WebView或者系統(tǒng)平臺自帶的控件蚌父,使用自身的高性能渲染引擎(Skia)自繪哮兰,界面開發(fā)語言使用dart,底層渲染引擎使用C, C++
我們可以看到最上層的
Material
和Cupertino
組件苟弛,這兩個什么玩意呢喝滞。其實很簡單
Cupertino
庫比蒂諾是硅谷核心城市之一,也是蘋果公司的總部膏秫,這就很容易理解了右遭,Cupertino
庫就是iOS風格的組件。Material
當然就是安卓主流風格的組件了缤削。
從架構圖可以看出窘哈,這兩個組件庫都是基于Widget
實現(xiàn)的,可以看出這個Widget
很基礎僻他,很重要啊宵距。
Flutter設計思想是一切皆是Widget,包括UI基礎控件吨拗,布局方式满哪,手勢等都是widget。
當我們新建一個Flutter工程之后劝篷,自帶的demo示例如下圖:
看一下demo代碼:
MaterialApp
包裹MyHomePage
,MyHomePage
包裹著Scaffold
,Scaffold
包裹著AppBar
和body
也可以增加bottomNavigationBar
等哨鸭。MaterialApp
繼承StatefulWidget,放在Main 入口內(nèi)函數(shù)中娇妓,初始化一個Material風格的App像鸡,一般配合Scaffold搭建AppUI架構。Scaffold
系統(tǒng)封裝好的腳手架哈恰,提供了設置頂部導航欄只估,底部導航欄,側邊欄着绷。App UI架構搭建完成之后蛔钙,看一下基本UI組件的使用和組合。
- 二.下面介紹一下Widget類:
abstract class Widget extends DiagnosticableTree{}
我們由此可知Widget是一個不能實例化的抽象類荠医。系統(tǒng)實現(xiàn)的它的兩個子類分別為StatefulWidget
和StatelessWidget
吁脱。
StatelessWidget
是無狀態(tài)的控件,很簡單彬向,創(chuàng)建之后兼贡,被它包裹的Widget上邊的數(shù)據(jù)就不在更新了,當然這個也不知絕對的娃胆,可以通過其他方法去更新StatelessWidget中Ui遍希,這個以后再說。
StatefulWidget 這個是有狀態(tài)的缕棵,創(chuàng)建StatefulWidget 同時必須創(chuàng)建對應的State類孵班,構建UI就放在了State類里邊涉兽,并且可以調用setState(){}
函數(shù)去從新使用新的狀態(tài)構建UI。所以在實際開發(fā)中篙程,我們要根據(jù)具體需求枷畏,選擇對應的Widget∈觯可以使用StatelessWidget完成的拥诡,盡可能的不要用StatefulWidget 。下面舉個例子:image1.jpg
StatelessWidget:比如說在一些靜態(tài)頁面構建時氮发,一旦UI構建之后便不需要再去更改UI渴肉,這時候可以使用StatelessWidget,比如一般App的關于我們頁面爽冕。
StatefulWidget :我們構建的是動態(tài)頁面仇祭,比如展示的數(shù)據(jù)是服務器返回來的,或者用戶進行交互颈畸,需要更新UI斬殺的數(shù)據(jù)乌奇。新建工程自帶的demo如下:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
效果如下:- 三.常用控件的學習
1.Text文本展示類
類似iOS的UILabel控件,系統(tǒng)提供了豐富的配置屬性眯娱。
const Text(this.data, {
Key key,
this.style,//單獨的style類礁苗,可以設置字體顏色,字體大小徙缴,字重试伙,字間距等強大功能
this.strutStyle,
this.textAlign,//對齊方式
this.textDirection,字體顯示方向
this.locale,
this.softWrap,
this.overflow,
this.textScaleFactor,
this.maxLines,//最大顯示行數(shù)
this.semanticsLabel,
}) : assert(data != null),
textSpan = null,
super(key: key);
當然也同樣支持不同樣式的復雜文本的顯示:
const Text.rich(this.textSpan, {
Key key,
this.style,
this.strutStyle,
this.textAlign,
this.textDirection,
this.locale,
this.softWrap,
this.overflow,
this.textScaleFactor,
this.maxLines,
this.semanticsLabel,
}) : assert(textSpan != null),
data = null,
super(key: key);
富文本顯示可以使用RichText。
2.Image
Image.asset
:從asset資源文件獲取圖片于样;
Image.network
:從網(wǎng)絡獲取圖片疏叨;
Image.file
:從本地資源文件回去圖片;
Image.memory
:從內(nèi)存資源獲取圖片穿剖;
FadeInImage
帶有一個占位圖的Image考廉,比如網(wǎng)絡較慢,或者網(wǎng)絡圖片請求失敗的時候携御,會有一個占位圖。
注意Image有一個Fit屬性既绕,用于設置圖片內(nèi)容適應方式啄刹,類似于iOS ImageView contenMode。
class GCImageTest extends StatefulWidget {
@override
_GCImageTestState createState() => _GCImageTestState();
}
class _GCImageTestState extends State<GCImageTest> {
Widget buildImage (url,BoxFit fit){
return Container(
child: Image.network(url,fit:fit,width: 350,height: 100,),
);
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
buildImage("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2942065216,1819114681&fm=27&gp=0.jpg", BoxFit.fill),
SizedBox(
height: 10,
),
buildImage("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2942065216,1819114681&fm=27&gp=0.jpg", BoxFit.cover),
SizedBox(
height: 10,
),
buildImage("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2942065216,1819114681&fm=27&gp=0.jpg", BoxFit.fitWidth),
SizedBox(
height: 10,
),
buildImage("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2942065216,1819114681&fm=27&gp=0.jpg", BoxFit.contain),
SizedBox(
height: 10,
),
buildImage("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2942065216,1819114681&fm=27&gp=0.jpg", BoxFit.fitHeight),
SizedBox(
height: 10,
),
buildImage("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2942065216,1819114681&fm=27&gp=0.jpg", BoxFit.scaleDown),
SizedBox(
height: 10,
),
FadeInImage.assetNetwork(
image:"",
placeholder:"lib/static/express_list_icon@2x.png",
)
],
);
}
}
3.按鈕
RaisedButton
:凸起的按鈕凄贩,周圍有陰影誓军,其實就是Android中的Material Design風格的Button ,繼承自MaterialButton疲扎。
FlatButton
:扁平化的按鈕昵时,繼承自MaterialButton捷雕。
OutlineButton
:帶邊框的按鈕,繼承自MaterialButton壹甥。
IconButton
:圖標按鈕,繼承自StatelessWidget救巷。
這些按鈕都可以通過設置shape來設置其圓角:
class _GCButtonTestState extends State<GCButtonTest> {
@override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
RaisedButton(
highlightColor: Colors.red,
color: Colors.orange,
child: Text("我是RaisedButton"),
onPressed: () {},
),
Container(
width: MediaQuery.of(context).size.width,
height: 80,
padding: EdgeInsets.all(20),
child: FlatButton(
shape: const RoundedRectangleBorder(
side: BorderSide.none,
borderRadius: BorderRadius.all(Radius.circular(50))),
highlightColor: Colors.red,
color: Colors.orange,
child: Text("我是FlatButton"),
onPressed: () {},
),
),
OutlineButton(
shape: const RoundedRectangleBorder(
side: BorderSide.none,
borderRadius: BorderRadius.all(Radius.circular(20))),
onPressed: () {},
child: Text("我是OutlineButton"),
),
],
),
);
}
}
效果如下:
4.TextField
用戶輸入控件:
Widget build(BuildContext context) {
return KeyboardAvoider(
focusPadding:20,
autoScroll: true,
child: Container(
padding: EdgeInsets.only(top: 20),
// color: Colors.green,
width: MediaQuery.of(context).size.width,
height:80,
child: TextField(
decoration: InputDecoration(
//設置邊框,占位符等
border: OutlineInputBorder(
borderSide: BorderSide(
width: 5,
color: Colors.grey,
),
borderRadius: BorderRadius.all(Radius.circular(20)),
),
contentPadding: EdgeInsets.all(10),
icon: Icon(Icons.text_fields),
hintText: "請輸入你的用戶名"),
keyboardType:TextInputType.text,//鍵盤類型
textInputAction: TextInputAction.done, //鍵盤 return 按鈕設置
maxLines: 1,
autocorrect: true, //是否自動更正
autofocus: false, //是否自動對焦
// obscureText: true, //是否是密碼
textAlign: TextAlign.center,
focusNode: _contentFocusNode,//控制是否為第一響應句柠, _contentFocusNode.unfocus();收起鍵盤浦译,F(xiàn)ocusScope.of(context).requestFocus(_contentFocusNode.unfocus)請求成為第一響應
onEditingComplete: () {
},
controller: controller, //監(jiān)聽輸入動作,可以在controller里設置默認值controller.text = "默認值";
onSubmitted:(String text){
print(text);
_contentFocusNode.unfocus();
} ,//提交信息
onChanged: (String text){
},
onTap: (){
},//文字輸入有變化
),
),
);
}
}
效果如下圖:注意的是在實際使用過程中TextField是不允許被鍵盤遮擋的溯职,當TextField父節(jié)點時可滾動視圖時精盅,系統(tǒng)會自動上拉,不被鍵盤遮擋谜酒。但是如果TextField父節(jié)點不是滾動視圖時候叹俏,可以使用第三方
KeyboardAvoider
進行包裹,這樣輸入時候也不會被鍵盤遮蓋僻族。controller
也必須主動銷毀
- 四常用布局類
1.0Flex布局
direction
:布局方向可以設置粘驰,縱向和橫向。
mainAxisAlignment
:主軸對齊方向鹰贵,如果橫向布局晴氨,那么Y軸是主節(jié)點。如果縱向布局那么X軸是主軸碉输。
crossAxisAlignment
:副軸對齊方式籽前。
children
:顧名思義上邊字節(jié)點集合。
這一點不理解的話敷钾,我舉個??:
class GCFlexRowlayoutTest extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Flex(
direction: Axis.horizontal,//布局方向
mainAxisAlignment: MainAxisAlignment.start,//主軸對齊方向枝哄,因為是橫向的布局,所以主軸是X方向
// crossAxisAlignment: CrossAxisAlignment.end,//副軸對齊方式阻荒,底部對齊
children: <Widget>[
Flexible(
flex: 1,//設置寬度比例
child: Container(
height: 100,
color: Colors.red,
),
),
Flexible(
flex: 2,
child: Container(
height: 150,
color: Colors.grey,
),
),
Flexible(
flex: 1,
child: Container(
height: 50,
color: Colors.green,
),
)
],
);
}
}
首先我先注釋掉crossAxisAlignment
:效果如下:
可見副軸(即這里的Y軸)挠锥,默認對齊方向是居中對齊。
下面我設置:
crossAxisAlignment: CrossAxisAlignment.end
效果如下:
此時設置的為Y軸的end方向對齊侨赡。其它對齊方式蓖租,可以自行試用一下。
1.0.1Row布局類
行布局類羊壹,是Flex的子類蓖宦,基本功能同F(xiàn)lex,布局方向為橫向布局
1.0.2Column布局類
列布局類油猫,是Flex的子類稠茂,基本功能同F(xiàn)lex,布局方向為縱向布局
實際開發(fā)中情妖,我們都是比較長使用這兩者嵌套進行復雜UI
構建睬关。
2.Stack層疊布局
如下圖效果:
代碼實現(xiàn)如下:
Widget build(BuildContext context) {
return Center(
child: Container(
height: 100,
width: 100,
child: Stack(
children: <Widget>[
ClipOval(
child: Image.asset(
"lib/static/express_list_icon@2x.png",
fit: BoxFit.fill,
),
),
Positioned(
left: 25,
right: 10,
top: 10,
child: Text("添加水印"),
),
Positioned(
right: 5,
top: 10,
child: ClipOval(
child: Container(
width: 10,
height:10,
color: Colors.red,
),
),
),
],
),
),
);
Stack配合Positioned,FractionalOffset進行定位布局诱担。
Positioned({
Key key,
this.left,
this.top,
this.right,
this.bottom,
this.width,
this.height,
@required Widget child,
})