Flutter 開發之元件一

JefferyChen發表於2019-10-16

Flutter 中基礎元件的介紹,用法也比較簡單。每個元件都是一個以類的形式存在。Flutter 的元件屬性也很多,我們不可能記得每一項,只有經常使用或者瞭解一些關鍵屬性,然後用到時再去檢視具體屬性。正所謂“流水的屬性,鐵打的元件”。

本篇主要介紹以下幾個元件:

  • Align-Align – 對齊元件
  • Bar – 元件
  • Box – 元件
  • Button – 元件

一、Align-Align – 對齊元件

一個 widget,它可以將其子 widget 對齊,並可以根據子 widget 的大小自動調整大小。

Flutter 開發之元件一

import 'package:flutter/material.dart';void main() => runApp(new MyApp());class MyApp extends StatelessWidget {  @override
  Widget build(BuildContext context) {    return MaterialApp(
      title: 'Align元件',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Align元件'),
        ),
        body:Container(//          width: 200.0,//          height: 200.0,
          color: Colors.red,
          child: Align(            //對齊方式
            //alignment: Alignment.bottomLeft,
            //對齊方式使用x,y來表示 範圍是-1.0 - 1.0
            alignment: Alignment(-0.5,-1.0),            //寬高填充的係數
            widthFactor: 3.0,
            heightFactor: 3.0,
            child: Container(
              color: Colors.green,
              width: 100.0,
              height: 50.0,
              child: Text('align',style: TextStyle(color: Colors.white),),
            ),
          ),
        ),
      ),
    );
  }
}

二、Bar – 元件

2.1 AppBar 元件

狀態列上的右側或左側按鈕,一個 Material Design 應用程式欄,由工具欄和其他可能的 widget(如 TabBar 和 FlexibleSpaceBar)組成。

Flutter 開發之元件一

import 'package:flutter/material.dart';void main() => runApp(new MyApp());class MyApp extends StatelessWidget {  @override
  Widget build(BuildContext context) {    return MaterialApp(
      title: 'AppBar元件',
      home: Scaffold(
        appBar: AppBar(
          title: Text('標題'),          //左側圖示
          leading: Icon(Icons.home),          //背景色
          backgroundColor: Colors.green,          //居中標題
          centerTitle: true,
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.print),
              tooltip: '列印',
              onPressed: (){},
            ),            //選單按鈕
            PopupMenuButton<String>(
              itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[                //選單項
                PopupMenuItem<String>(
                  value: 'friend',
                  child: Text('分享到朋友圈'),
                ),
                PopupMenuItem<String>(
                  value: 'download',
                  child: Text('下載到本地'),
                ),
              ],
            ),
          ],
        ),
        body: Container(),
      ),
    );
  }
}

2.2 bottomNavigationBar

底部導航條,可以很容易地在 tap 之間切換和瀏覽頂級檢視。
Flutter 開發之元件一

    return BottomNavigationBar(      //底部按鈕型別 固定樣式
      type: BottomNavigationBarType.fixed,      //按鈕大小
      iconSize: 24.0,      //點選裡面的按鈕回撥的函式
      onTap: _onItemTapped,      //當前選中項索引 高亮顯示
      currentIndex: _currentIndex,      //當型別為fixed時,選中項的顏色
      fixedColor: Colors.red,
      items: <BottomNavigationBarItem>[
        BottomNavigationBarItem(title: Text('聊天'),icon: Icon(Icons.chat)),
        BottomNavigationBarItem(title: Text('朋友圈'),icon: Icon(Icons.refresh)),
        BottomNavigationBarItem(title: Text('我的'),icon: Icon(Icons.person)),
      ],
    );

2.3 ButtonBar

未端對齊按鈕容器  ButtonBar

      child: ButtonBar(        //對齊方式 預設為末端end
        alignment: MainAxisAlignment.spaceAround,
      ),

2.4 FlexibleSpaceBar

可摺疊的應用欄  FlexibleSpaceBar

        body: NestedScrollView(
            headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled){              return <Widget>[
                SliverAppBar(                  //展開高度
                  expandedHeight: 150.0,                  //是否隨著滑動隱藏標題
                  floating: false,                  //是否固定在頂部
                  pinned: true,                  //可摺疊的應用欄
                  flexibleSpace: FlexibleSpaceBar(
                    centerTitle: true,
                    title: Text(                      '可摺疊的元件',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.0,
                      ),
                    ),
                  ),
                ),
              ];
            },
            body: Center(
              child: Text('向上提拉,檢視效果'),
            )
        ),
      ),
    );

2.5 SliverAppBar

Sliver應用欄  SliverAppBar

 body: NestedScrollView(
            headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled){              return <Widget>[
                SliverAppBar(                  //是否預留高度
                  primary:true,                  //標題前面顯示的一個控制元件
                  leading: Icon(Icons.home),                  //操作按鈕
                  actions: <Widget>[
                    Icon(Icons.add),
                    Icon(Icons.print),
                  ],                  //設定陰影值
                  elevation: 10.0,                  //是否固定在頂部
                  pinned: true,                  //可擴充套件區域高度
                  expandedHeight: 200.0,                  //與floating結合使用
                  snap: false,                  //是否隨著滑動隱藏標題
                  floating: false,                  //擴充套件區域
                  flexibleSpace: FlexibleSpaceBar(
                    centerTitle: true,
                    title: Text(                      '這是一個很酷的標題',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.0,
                      ),
                    ),
                  ),
                ),
              ];
            },
            body: Center(
              child: Text(                '拖動試試'
              ),
            ),
        ),

2.6 SnackBar

螢幕底部訊息

return Center(
      child: GestureDetector(
        onTap: () {          final snackBar = new SnackBar(            //提示資訊
            content: Text('這是一個SnackBar'),            //背景色
            backgroundColor: Colors.green,            //操作
            action: SnackBarAction(
              textColor: Colors.white,
              label: '撤消',
              onPressed: () {},
            ),            //持續時間
            duration: Duration(minutes: 1),
          );
          Scaffold.of(context).showSnackBar(snackBar);
        },
        child: Text('顯示螢幕底部訊息'),
      ),
    );

2.7 TabBar

選項卡,一個顯示水平選項卡的 Material Design widget。

Flutter 開發之元件一

class DemoPageState extends State<DemoPage> with SingleTickerProviderStateMixin {
  ScrollController _scrollViewController;
  TabController _tabController;  @override
  void initState(){    super.initState();
    _scrollViewController = new ScrollController();    //長度要和展示部分的Tab數一致
    _tabController = new TabController(vsync: this,length: 6);
  }  @override
  void dispose(){    super.initState();
    _scrollViewController.dispose();
    _tabController.dispose();    super.dispose();
  }  @override
  Widget build(BuildContext context) {    return SizedBox(
      height: 500.0,
      child: Scaffold(
        appBar: AppBar(
          title: Text('選項卡'),          //前置圖示
          leading: Icon(Icons.home),          //應用欄背景色
          backgroundColor: Colors.green,          //選項卡
          bottom: TabBar(
            controller: _tabController,            //是否可以滾動
            isScrollable: true,
              tabs: <Widget>[
                Tab(text: '科技',icon: Icon(Icons.camera),),
                Tab(text: '吃飯',icon: Icon(Icons.print),),
                Tab(text: '體育',icon: Icon(Icons.favorite),),
                Tab(text: '娛樂',icon: Icon(Icons.share),),
                Tab(text: '電影',icon: Icon(Icons.video_call),),
                Tab(text: '教育',icon: Icon(Icons.airline_seat_flat_angled),),
              ]
          ),
        ),        //選項卡檢視
        body: TabBarView(controller: _tabController,
            children: <Widget>[
              Text('選項卡1'),
              Text('選項卡2'),
              Text('選項卡3'),
              Text('選項卡4'),
              Text('選項卡5'),
              Text('選項卡6'),
            ]
        ),
      ),
    );
  }
}

三、Box – 元件

3.1 ConstrainedBox

限定最大最小寬高容器,對其子項施加附加約束的 widget

Flutter 開發之元件一

              //新增一個指定大小的盒子,限定其最大最小寬高
              ConstrainedBox(
                constraints: const BoxConstraints(
                  minWidth: 100.0,                  minHeight: 20.0,                  maxHeight: 60.0,                  maxWidth: 200.0,
                ),                child: Container(
                  width: 250,                  height: 80,                  child: Text(                    'width>maxWidth height>maxHeight',                    style: TextStyle(color: Colors.white),
                  ),                  color: Colors.green,
                ),
              ),

3.2 DecoratedBox

裝飾容器,DecoratedBox 可以在其子 widget 繪製前(或後)繪製一個裝飾 Decoration(如背景、邊框、漸變等 )。

DecoratedBox

            //新增裝飾
            child: DecoratedBox(                //裝飾定位 DecorationPosition.background背景模式 DecorationPosition.foreground前景模式
                position: DecorationPosition.background,                decoration: BoxDecoration(                  //背景色
                  color: Colors.grey,                  //設定背景圖片
                  image: DecorationImage(                    //圖片填充方式
                    fit: BoxFit.cover,                    image: ExactAssetImage('assets/view.jpeg'),
                  ),                  //邊框弧度
                  //borderRadius: BorderRadius.circular(10.0),
                  border: Border.all(                    //邊框顏色
                    color: Colors.red,                    //邊框粗細
                    width: 6.0,
                  ),                  //邊框樣式
                  shape: BoxShape.rectangle,
                ),              child: Text('定位演示',style: TextStyle(fontSize: 36.0,color: Colors.green),),
            ),

3.3 FittedBox

填充容器,按自己的大小調整其子 widget 的大小和位置。  FittedBox

/*
          BoxFit.fill  //全部顯示,顯示可能拉伸,充滿
          BoxFit.contain    //全部顯示,顯示原比例,不需充滿
          BoxFit.cover    //顯示可能拉伸,可能裁剪,充滿
          BoxFit.fitWidth    //顯示可能拉伸,可能裁剪,寬度充滿
          BoxFit.fitHeight    //顯示可能拉伸,可能裁剪,高度充滿
          BoxFit.none
          BoxFit.scaleDown   //效果和contain差不多,但是此屬性不允許顯示超過源圖片大小,可小不可大
*/class MyApp extends StatelessWidget {  @override
  Widget build(BuildContext context) {    return new MaterialApp(
      title: 'FittedBox填充容器',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('FittedBox填充容器'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
            Container(
                width: 300.0,
                height: 300.0,
                color: Colors.grey,
                child: FittedBox(                  //填充型別
                  fit: BoxFit.none,                  //居中對齊
                  alignment: Alignment.center,
                  child: Image.asset('assets/view.jpeg'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

3.4 OverflowBox

溢位容器,對其子項施加不同約束的 widget,它可能允許子項溢位父級。  OverflowBox

          //溢位容器
          child: OverflowBox(            //對齊方式
            alignment: Alignment.topLeft,            //限制條件
            maxWidth: 300.0,            maxHeight: 500.0,            child: Container(
              color: Colors.blueGrey,              width: 400.0,              height: 400.0,
            ),
          ),

3.5 RotatedBox

旋轉容器,可以延順時針以90度的倍數旋轉其子 widget。 RotatedBox

        body: Center(          child: Column(            children: <Widget>[              SizedBox(
                height: 20.0,
              ),
              RotatedBox(
                child: Text('ABCDE',style: TextStyle(fontSize: 28.0),),                //旋轉次數 每次旋轉一圈的1/4
                quarterTurns: 1,
              ),
              SizedBox(
                height: 20.0,
              ),
              RotatedBox(
                child: Text('ABCDE',style: TextStyle(fontSize: 28.0),),                quarterTurns: 2,
              ),
              SizedBox(
                height: 20.0,
              ),
              RotatedBox(
                child: Text('ABCDE',style: TextStyle(fontSize: 28.0),),                quarterTurns: 3,
              ),
              SizedBox(
                height: 20.0,
              ),
              RotatedBox(
                child: Text('ABCDE',style: TextStyle(fontSize: 28.0),),                quarterTurns: 4,
              ),
            ],
          ),
        ),

3.6 SizedBox

指定寬高容器,一個特定大小的盒子。這個 widget 強制它的孩子有一個特定的寬度和高度。如果寬度或高度為 NULL,則此 widget 將調整自身大小以匹配該維度中的孩子的大小。

        body:Center(          //指定寬高容器 child不允許超出指定大小的範圍
          child: SizedBox(
            width: 200.0,            height: 200.0,            //限定圖片大小
            child: Image.asset('assets/cat.jpeg'),            //子元素//            child: Container(//              width: 10.0,//              height: 10.0,//              color: Colors.green,//            ),
          ),
        ),

四、Button – 元件

4.1 DropdownButton

下拉按鈕  DropdownButton

class DropdownButtonDemo extends StatelessWidget {  List<DropdownMenuItem> generateItemList(){
    final List<DropdownMenuItem> items = new List();
    final DropdownMenuItem item1 = new DropdownMenuItem(child: Text('北京'),value: '北京',);
    final DropdownMenuItem item2 = new DropdownMenuItem(child: Text('上海'),value: '上海',);
    final DropdownMenuItem item3 = new DropdownMenuItem(child: Text('廣州'),value: '廣州',);
    final DropdownMenuItem item4 = new DropdownMenuItem(child: Text('深圳'),value: '深圳',);
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);    return items;
  }
  @override
  Widget build(BuildContext context) {    return DropdownButton(      //提示文字
      hint: Text('請選擇一個城市'),      //下拉選單項資料
      items: generateItemList(),      value: selectItemValue,      //下拉三角型圖示大小
      iconSize: 48.0,      //下拉文字樣式
      style: TextStyle(
        color: Colors.green,
      ),      //設定陰影高度
      elevation: 24,      //將下拉框設定為水平填充成父級
      isExpanded: true,      //下拉改變事件
      onChanged: (T){        var obj = T;
      },
    );
  }
}

4.2 FlatButton

一個扁平的 Material 按鈕.
Flutter 開發之元件一

FlatButton

</center>

            FlatButton.icon(
                onPressed: (){
                },
                icon: Icon(Icons.print,size: 36.0,),
                label: Text('預設按鈕',style: TextStyle(fontSize: 36.0),),
            ),
           FlatButton(              //文字
              child: Text(                'Success',
                style: TextStyle(fontSize: 26.0),
              ),              //按鈕背景色
              color: Colors.green,              //按鈕亮度
              colorBrightness: Brightness.dark,              //失效時的背景色
              disabledColor: Colors.grey,              //失效時的文字色
              disabledTextColor: Colors.grey,              //文字顏色
              textColor: Colors.white,              //按鈕主題 ButtonTheme ButtonThemeData ButtonTextTheme ThemeData
              textTheme: ButtonTextTheme.normal,              //墨汁飛濺的顏色
              splashColor: Colors.blue,              //抗鋸齒能力
              clipBehavior: Clip.antiAlias,              //內邊距
              padding: new EdgeInsets.only(
                bottom: 5.0,
                top: 5.0,
                left: 20.0,
                right: 20.0,
              ),
            ),

4.3 FloatingActionButton

跟 iOS 手機的小白點一樣,一個圓形圖示按鈕,它懸停在內容之上,以展示應用程式中的主要動作。FloatingActionButton 通常用於Scaffold.floatingActionButton 欄位。

Flutter 開發之元件一

FloatingActionButton

</center>

            FloatingActionButton(              //圖示
              child: const Icon(Icons.person),              //提示資訊
              tooltip: '這是一個自定義的按鈕',              //背景色
              backgroundColor: Colors.blue,              //前景色
              foregroundColor: Colors.white,              //hero效果使用
              heroTag: null,              //未點選時的陰影
              elevation: 8.0,              //點選時的陰影
              highlightElevation: 16.0,              onPressed: () {},              // 是否為“mini”型別,預設為false,FAB 分為三種型別:regular, mini, and extended
              mini: false,              //圓角方形的樣式
              shape: RoundedRectangleBorder(
                side: BorderSide(
                  width: 2.0,                  color: Colors.white,                  style: BorderStyle.solid,
                ),                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(8.0),                  topLeft: Radius.circular(8.0),                  bottomRight: Radius.circular(8.0),                  bottomLeft: Radius.circular(8.0),
                ),
              ),
            ),

4.4 IconButton

一個 Material 圖示按鈕,點選時會有水波動畫。

IconButton</cneter>

           child: IconButton(              //圖示
              icon: Icon(Icons.print),              //圖示大小
              iconSize: 48.0,              //根據父容器來決定圖示的位置
              alignment: AlignmentDirectional.center,
              color: Colors.green,              //墨汁飛濺效果
              splashColor: Colors.blue,
              padding: EdgeInsets.only(bottom: 5.0, top: 5.0, left: 30.0, right: 30.0),              //提示文字
              tooltip: '一個列印圖示',              //按下
              onPressed: () {},
            ),

4.5 RaisedButton

Material Design 中的 button, 一個凸起的材質矩形按鈕。

Flutter 開發之元件一

RaisedButton
</center>

     child: RaisedButton(        //文字
        child: Text(          '點選登入按鈕',
          style: TextStyle(fontSize: 26.0),
        ),        //按鈕背景色
        color: Colors.green,        //按鈕亮度
        colorBrightness: Brightness.dark,        //失效時的背景色
        disabledColor: Colors.grey,        //失效時的文字色
        disabledTextColor: Colors.grey,        //文字顏色
        textColor: Colors.white,        //按鈕主題 ButtonTheme ButtonThemeData ButtonTextTheme ThemeData
        textTheme: ButtonTextTheme.normal,        //墨汁飛濺的顏色
        splashColor: Colors.blue,        //抗鋸齒能力
        clipBehavior: Clip.antiAlias,        //內邊距
        padding: new EdgeInsets.only(
          bottom: 5.0,
          top: 5.0,
          left: 20.0,
          right: 20.0,
        ),
        shape: RoundedRectangleBorder(
          side: new BorderSide(
            width: 2.0,
            color: Colors.white,
            style: BorderStyle.solid,
          ),
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(10.0),
            topLeft: Radius.circular(10.0),
            bottomLeft: Radius.circular(10.0),
            bottomRight: Radius.circular(10.0),
          ),
        ),
        onPressed: () {          print('按鈕按下操作');
        },
      ),

4.6 RawMaterialButton

RawMaterialButton

     body: RawMaterialButton(
          onPressed: (){},          textStyle: TextStyle(fontSize: 28.0,color: Colors.black,),          //文字
          child: Text('RawMaterialButton元件'),          //高亮時的背景色
          highlightColor: Colors.red,          //墨汁飛濺
          splashColor: Colors.blue,          //搞鋸齒
          clipBehavior: Clip.antiAlias,          padding: EdgeInsets.only(bottom: 5.0,top: 5.0,left: 30.0,right: 30.0),          //高亮時的陰影
          highlightElevation: 10.0,
        ),


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69950672/viewspace-2660271/,如需轉載,請註明出處,否則將追究法律責任。

相關文章