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類里邊,并且可以調(diào)用setState(){}函數(shù)去從新使用新的狀態(tài)構建UI。所以在實際開發(fā)中,我們要根據(jù)具體需求,選擇對應的Widget??梢允褂肧tatelessWidget完成的,盡可能的不要用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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容