Flutter的基礎UI的搭建

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成apkandroid上運行睛榄,或是生成ipaiOS運行。

一般傳統(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++
Flutter_image.png

一臉懵逼.png

我們可以看到最上層的MaterialCupertino組件苟弛,這兩個什么玩意呢喝滞。
其實很簡單Cupertino庫比蒂諾是硅谷核心城市之一,也是蘋果公司的總部膏秫,這就很容易理解了右遭,Cupertino庫就是iOS風格的組件。Material當然就是安卓主流風格的組件了缤削。

從架構圖可以看出窘哈,這兩個組件庫都是基于Widget實現(xiàn)的,可以看出這個Widget很基礎僻他,很重要啊宵距。

Widget重點.jpeg

Flutter設計思想是一切皆是Widget,包括UI基礎控件吨拗,布局方式满哪,手勢等都是widget。

常用的Widget.jpg

當我們新建一個Flutter工程之后劝篷,自帶的demo示例如下圖:

IMG_6758.JPG

看一下demo代碼:MaterialApp包裹MyHomePage,MyHomePage包裹著Scaffold,Scaffold包裹著AppBarbody也可以增加bottomNavigationBar等哨鸭。
AppDemo首頁.jpg

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)的它的兩個子類分別為StatefulWidgetStatelessWidget吁脱。
    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的關于我們頁面爽冕。


demoLess.jpg

效果如下
demoLessUI.jpg

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.
    );
  }
}

效果如下:
demo2.gif
  • 三.常用控件的學習
    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",
        )

      ],
    );
  }
}
圖片Demo.jpg
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"),
          ),
        ],
      ),
    );
  }
}

效果如下:


buttonDemo.jpg
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: (){
              
            },//文字輸入有變化
          ),
        ),
    );
  }
}

效果如下圖:
TextFieldDemo.jpg

注意的是在實際使用過程中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:效果如下:

FlexDemo1.jpg

可見副軸(即這里的Y軸)挠锥,默認對齊方向是居中對齊。
下面我設置:crossAxisAlignment: CrossAxisAlignment.end
效果如下:
FlexDemo2.jpg

此時設置的為Y軸的end方向對齊侨赡。其它對齊方式蓖租,可以自行試用一下。

1.0.1Row布局類

行布局類羊壹,是Flex的子類蓖宦,基本功能同F(xiàn)lex,布局方向為橫向布局

1.0.2Column布局類

列布局類油猫,是Flex的子類稠茂,基本功能同F(xiàn)lex,布局方向為縱向布局

實際開發(fā)中情妖,我們都是比較長使用這兩者嵌套進行復雜UI
構建睬关。

2.Stack層疊布局

如下圖效果:


stackDemo.jpg

代碼實現(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,
  })
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市电爹,隨后出現(xiàn)的幾起案子蔫仙,更是在濱河造成了極大的恐慌,老刑警劉巖藐不,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件匀哄,死亡現(xiàn)場離奇詭異,居然都是意外死亡雏蛮,警方通過查閱死者的電腦和手機涎嚼,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來挑秉,“玉大人法梯,你說我怎么就攤上這事∠牛” “怎么了立哑?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長姻灶。 經(jīng)常有香客問我铛绰,道長,這世上最難降的妖魔是什么产喉? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任捂掰,我火速辦了婚禮,結果婚禮上曾沈,老公的妹妹穿的比我還像新娘这嚣。我一直安慰自己,他們只是感情好塞俱,可當我...
    茶點故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布姐帚。 她就那樣靜靜地躺著,像睡著了一般障涯。 火紅的嫁衣襯著肌膚如雪罐旗。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天唯蝶,我揣著相機與錄音尤莺,去河邊找鬼。 笑死生棍,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的媳谁。 我是一名探鬼主播涂滴,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼友酱,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了柔纵?” 一聲冷哼從身側響起缔杉,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎搁料,沒想到半個月后或详,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡郭计,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年霸琴,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片昭伸。...
    茶點故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡梧乘,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出庐杨,到底是詐尸還是另有隱情选调,我是刑警寧澤,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布灵份,位于F島的核電站仁堪,受9級特大地震影響,放射性物質發(fā)生泄漏填渠。R本人自食惡果不足惜弦聂,卻給世界環(huán)境...
    茶點故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望揭蜒。 院中可真熱鬧横浑,春花似錦、人聲如沸屉更。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽瑰谜。三九已至欺冀,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間萨脑,已是汗流浹背隐轩。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留渤早,地道東北人职车。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親悴灵。 傳聞我的和親對象是個殘疾皇子扛芽,可洞房花燭夜當晚...
    茶點故事閱讀 45,092評論 2 355

推薦閱讀更多精彩內(nèi)容