Flutter 學習(四) 基礎控件

前面幾篇文章咱們學些了Flutter 開發的dart語言基礎 ,接下來的文章將開始介紹在flutter 中咱們經常使用的控件 以及控件的屬性 動畫 以及自定義控件方式...ios

Widget

MaterialApp

主頁面根佈局bash

//頁面主佈局
  MaterialApp(
      //內容腳手架 顯示標題 內容 drawLayout 底部導航
      home: Scaffold(
      //標題
         appBar: AppBar(
        title: Text('MD 主題'),
        //居中
        centerTitle: true,
        //圖標
        leading: Icon(Icons.star),
        //陰影
        elevation: 0.0,
        actions: <Widget>[
          Icon(Icons.search),
          Icon(Icons.more_horiz),
        ],
       ),
        //顯示的Ui
        body: Center()
        )

複製代碼

1. container : 容器

能夠當作是個viewgroup 對要展現的控件進行修飾,下面這個例子就包裹了一個Text控件.只介紹經常使用的屬性 ,其餘屬性能夠自行學習,都不會很難理解.網絡

Center(
          child: Container(
             //裝飾器 定義控件的背景樣式  BoxDecoration   DecorationImage
             decoration: BoxDecoration(
             //背景顏色
              color: Colors.black,
              //高斯模糊背景
              boxShadow: [BoxShadow(color: Colors.green, blurRadius: 5.0)],
              //漸變色  也能夠設置 扇形漸變 原型漸變
              gradient: LinearGradient(colors: [Colors.black]),
              //形狀 BoxShape.circle 能夠做爲圓形頭像進行配置
              shape: BoxShape.circle,
              //圖片背景
              image: DecorationImage(
                    //本地資源設置  能夠是網絡 等其它方式 須要替換AssetImage
                  image: AssetImage("assets/images/ic_avatar_default.png")),
                //邊界線條
              border: Border.all(color: Color(0xffff0000), width: 10.0),
              //邊界圓角弧度
              borderRadius: const BorderRadius.all(const Radius.circular(30.0)),
            ),
            //約束 寬高約束 通常不用這麼設置,直接設置 Container的 height  width就能夠
            constraints: BoxConstraints.expand(
              width: 200,
              height:
                  Theme.of(context).textTheme.display1.fontSize * 1.1 + 100.0,
            ),
            //內邊距 後邊必需要EdgeInsets.all(8.0) 這種形式,也能夠單獨設置上下左右間距
            padding: EdgeInsets.all(8.0),
            //對齊方式 居中 居左 居上.....
            alignment: Alignment.center,
            //圖形變換對這個控件 進行旋轉 位移...
            transform: Matrix4.rotationZ(0.1),
            //包裹子控件
            child: Text('Hello World',
                style: Theme.of(context)
                    .textTheme
                    .display1
                    .copyWith(color: Colors.white)),
           
          ),
        ),
        ),
複製代碼

2. Text 文字顯示

Android上的TextView ,用於文字顯示app

Text(
                //文字展現
                'text使用案例 ,的價格哈接口上的幹哈接口的規劃局考試大綱還以爲黃金卡好貴收到貨撒金龜換酒後視鏡的客觀化科技好四大皆空更好看 ',
                //最大行數
                maxLines: 1,
                // 設置成false 超出顯示區域的文字不會在現實 只顯示一行文字
                softWrap: true,
                //文字對齊方式
                textAlign: TextAlign.center,
                //顯示方式 下面這個顯示不了的字 後面會加上...
                overflow: TextOverflow.ellipsis,
                //文字樣式
                style: TextStyle(
                    //字體顏色
                    color: Colors.green,
                    //加粗
                     fontWeight: FontWeight.bold,
                    //字體大小
                    fontSize:25,
                    //字體樣式 斜體 直體
                    fontStyle: FontStyle.normal,
                    //字符間距
                    letterSpacing: 15,
                    //基線對齊
                    textBaseline: TextBaseline.ideographic,
                    //單詞間距
                    wordSpacing: 12,
                    //上劃線 下劃線 中劃線
                    decoration: TextDecoration.lineThrough,
                    //線條樣式 虛線 直線
                    decorationStyle: TextDecorationStyle.dashed),
              ),
複製代碼

3. RichText 富文本

富文本基本屬性相似 Textasync

RichText(
                text: TextSpan(
                    text: 'textgjdgasdjkg',
                    style: TextStyle(color: Colors.red).apply(),
                    //富文本須要一段一段設置
                    children: <TextSpan>[
                    //第一條文案的樣式若是不設置耿直外層的樣式
                      TextSpan(text: '121345654654'),
                      TextSpan(
                        //手勢識別器,點擊事件捕獲
                          recognizer: TapGestureRecognizer()
                            ..onTap = () async {
                              String url = "http://www.baidu.com";
                              if (await canLaunch(url)) {
                                launch(url);
                              } else {
                                throw ('請求地址{$url}');
                              }
                            },
                          text: '百度',
                          style: TextStyle(
                              color: Colors.yellow,
                              decoration: TextDecoration.lineThrough,
                              decorationStyle: TextDecorationStyle.dashed)),
                    ]),
              ),
複製代碼

4. BoxSize

盒子類型,用於控件之間的間距ide

SizedBox(
                height: 30,
                width: 30,
              ),
複製代碼

5. Center

居中控件可配置子控件居中顯示佈局

6. Column Row

橫向縱向顯示學習

Column(
             //副軸對齊  也就是內部空間左右對齊方式
            crossAxisAlignment: CrossAxisAlignment.start,
            //主軸對齊 上下方向的對齊方式
            mainAxisAlignment: MainAxisAlignment.start,
            )

複製代碼

7. Expanded

這個控件通常會在Row 裏使用當第一個Text控件內容超出顯示區域 會出現警告,能夠用這個控件包裹下,而後折行顯示字體

8. Button

能夠設置按鈕顏色 等其餘屬性動畫

  • IconButton 圖標按鈕
IconButton(
              //圖標
                icon: Icon(Icons.http),
                //點擊事件
                onPressed: () {},
              ),
複製代碼
  • RaisedButton 能夠顯示本身的樣式的按鈕 而且會顯示海拔樣式
RaisedButton(
                child: Text('raisedButton'),
                onPressed: () {},
              ),
            
複製代碼
  • FlatButton /鋪平的按鈕
FlatButton(
                child: Text('FlatButton'),
                onPressed: () {},
              ),
  
複製代碼
  • FlatButton.icon //圖標加控件的按鈕
FlatButton.icon(
                  onPressed: () {},
                  icon: Icon(Icons.build),
                  label: Text('FlatButton.icon'))
複製代碼

9. Icon

圖標顯示

Icon(Icons.contact)
複製代碼

10. Image

圖片加載方式

  • Image.network("www.baidu.com") //網絡加載
  • Image.asset( 'assets/images/tzd.jpg'),//asset加載
  • MemoryImage(bytes) //內存加載 須要先獲取bytes
rootBundle.load('assets/images/tzd.jpg').then((data) {
      if (mounted) {
        setState(() {
          bytes = data.buffer.asUint8List();
        });
      }
複製代碼
  • Image.file(file) //文件加載

11.form

表單提交 相似Android上的輸入框 ,下面這個是登錄案例 ,須要咱們先獲取惟一索引_loginState 而後去獲取當前狀態去作驗證合法性,以及存儲數據

void _login() {
    var state = _loginState.currentState;
    if (state.validate()) {
      state.save();
      Scaffold.of(state.context).showSnackBar(SnackBar(
          content: Text('_userName====$_userName+++_password=====$_password')));
    }
  }
複製代碼
child: Column(
              children: <Widget>[
                Form(
                    //位移索引
                    key: _loginState,
                    child: Column(
                      children: <Widget>[
                        TextFormField(
                          decoration: InputDecoration(labelText: '請輸入用戶名'),
                          //保存方法
                          onSaved: (value) {
                            print('onSave');
                            _userName = value;
                          },
                          //提交監聽
                          onFieldSubmitted: (value) {
                            print('onFieldSubmitted');
                          },
                        ),
                        TextFormField(
                          decoration: InputDecoration(labelText: '請輸入密碼'),
                          onSaved: (value) {
                            print('onSave');
                            _password = value;
                          },
                          onFieldSubmitted: (value) {
                            print('onFieldSubmitted');
                          },
                          //模糊文字.隱藏明文
                          obscureText: true,
                          //驗證輸入的正確性
                          validator: (value) {
                            return value.length < 6 ? '密碼最少6位' : null;
                          },
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 50),
                          width: 300,
                          height: 45,
                          child: RaisedButton(
                            child: Text('登錄'),
                            onPressed: () {
                              _login();
                            },
                          ),
                        )
                      ],
                    ))
              ],
複製代碼

12. ListView

列表展現使用方式分幾種

  • ListView.builder()方式 能夠設置條目數量 條目顯示控件
ListView.builder(
             //滑動方向 縱向 橫向
                scrollDirection: Axis.horizontal,
                //數量
              itemCount: 40,
              //條目佈局
              itemBuilder: (context, index) {
                if (index.isOdd) {
                  return Divider();
                }
                return ListTile(
                    leading: Icon(Icons.ac_unit),
                    title: Text('$index主標題'),
                    subtitle: Text('副標題'),
                    trailing: Icon(Icons.arrow_forward_ios));
              })
複製代碼
  • List.generate方式
ListView(
      scrollDirection: Axis.horizontal,
      children: List.generate(50, (index) {
        return Text(
          '$index',
          style: TextStyle(fontSize: 30),
        );
      }),
    )
複製代碼
  • ListView children 控件集合方式 不靈活
ListView(
      children: <Widget>[
        Divider(),
        ListTile(
          leading: Icon(Icons.ac_unit),
          title: Text('主標題'),
          subtitle: Text('副標題'),
          trailing: Icon(Icons.arrow_forward_ios),
        ),
        Divider(),
        ListTile(
          leading: Icon(Icons.ac_unit),
          title: Text('主標題'),
          subtitle: Text('副標題'),
          trailing: Icon(Icons.arrow_forward_ios),
        ),
        Divider(),
      ],
    )
複製代碼

13. GridView

  • GridView.builder()
GridView.builder(
            //數量
            itemCount: 50,
            //顯示方式 crossAxisCount 一行個數  crossAxisSpacing,mainAxisSpacing 主軸副軸間距
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,crossAxisSpacing: 6, mainAxisSpacing: 6),
                  //條目控件
              itemBuilder: (context, index) {
                return Container(
                    color: Colors.red,
                    child: Text('$index條目'));
              }) //buildGridViewCount(),
          ),
複製代碼
  • GridView.count
GridView.count(
    //一行數量
      crossAxisCount: 5,
      //條目的長寬比
      childAspectRatio: 3 / 4,
      //滑動方向
      scrollDirection: Axis.vertical,
      //總數量 個條目控件設置
      children: List.generate(50, (index) {
        return Container(
            margin: EdgeInsets.all(10),
            color: Colors.red,
            child: Text('$index條目'));
      }),
    )
複製代碼

14 ListTile

系統封裝好的 標題 描述 圖標 箭頭 控件

ListTile(
          leading: Icon(Icons.ac_unit),
          title: Text('主標題'),
          subtitle: Text('副標題'),
          trailing: Icon(Icons.arrow_forward_ios),
        )
複製代碼

15. Card

卡片佈局

Card(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(10.0))),
      child: Column( )
    )

複製代碼

16.Padding

Padding(
                padding: const EdgeInsets.all(15.0),
                child: Icon(Icons.contact_mail),
              )
複製代碼

17. Scaffold 腳手架

  • AppBar標題
appBar: AppBar(
        title: Text('MD 主題'),
        //居中
        centerTitle: true,
        //圖標
        leading: Icon(Icons.star),
        //陰影
        elevation: 0.0,
        //菜單
        actions: <Widget>[
          Icon(Icons.search),
          Icon(Icons.more_horiz),
        ],
      ),
複製代碼
  • floatingActionButton
floatingActionButton: FloatingActionButton(
          child: Icon(Icons.access_alarm),
          <!--背景色-->
          backgroundColor: Colors.yellow,
          <!--這個能夠給圖片添加顏色-->
          foregroundColor: Colors.red,
          tooltip: '長按',
//          shape: RoundedRectangleBorder(),
          onPressed: () {
          //跳轉操做 後續會介紹
            Navigator.pushNamed(context, "/newPager");
          }),
複製代碼
  • BottomNavigationBar
bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.list), title: Text('主頁')),
          BottomNavigationBarItem(icon: Icon(Icons.save), title: Text('通信錄')),
          BottomNavigationBarItem(icon: Icon(Icons.print), title: Text('訂單')),
          BottomNavigationBarItem(icon: Icon(Icons.launch), title: Text('個人')),
        ],
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
複製代碼
  • drawer
Drawer(
//        elevation: 30,
      child: ListView(
        children: <Widget>[
        //顯示標題描述  頭像 圖標 北京
          UserAccountsDrawerHeader(
            accountName: Text(
              "劉澤",
              style: TextStyle(color: Colors.black),
            ),
            accountEmail: Text(
              '835052259@qq.com',
              style: TextStyle(color: Colors.black),
            ),
            //頭像
            currentAccountPicture: CircleAvatar(
              backgroundImage: NetworkImage(
                  "https://img5.duitang.com/uploads/item/201411/18/20141118201614_8Bjax.thumb.700_0.jpeg"),
            ),
            otherAccountsPictures: <Widget>[Icon(Icons.camera)],
            /背景
            decoration: BoxDecoration(
                image: DecorationImage(
                    fit: BoxFit.fill,
                    image: NetworkImage(
                        "http://img.jituwang.com/uploads/allimg/150109/258940-15010922123023.jpg"))),
          ),
        //這個能夠彈出關於的彈框提示
          AboutListTile(
            child: Text('關於'),
            icon: Icon(Icons.add_box),
            applicationName: "版本升級",
            applicationVersion: '1.0.0',
            applicationIcon: Icon(Icons.launch),
            applicationLegalese: '描述',
            aboutBoxChildren: <Widget>[
              Text('按鈕1'),
              Text('按鈕2'),
              Text('按鈕3'),
            ],
          )
        ],
      ),
    )
複製代碼

18. CircleAvatar

圓形頭像控件

未完待續

下一篇文章將介紹 dialog 關於位置的控件 以及 在ios風格下 Cupertino 的應用

相關文章
相關標籤/搜索