Flutter Widget(1):基礎Widget

1.Container

  • Container類似于android中的ViewGroup。可以實現設置背景顏色、背景圖片、加邊框、加圓角、各方向對齊等功能,是項目中經常用到的Widget。
  • 對于一個沒有子Widget的Container,在沒有一些約束的條件時,它會盡可能的大;而一旦有了約束或者子Widget,它就會變得盡可能小。
  • key:Container唯一標識符,用于查找更新。
  • alignment:控制child的對齊方式,如果container或者container父節點尺寸大于child的尺寸,這個屬性設置會起作用,有很多種對齊方式。
  • padding:decoration內部的空白區域,如果有child的話,child位于padding內部。padding與margin的不同之處在于,padding是包含在content內,而margin則是外部邊界,設置點擊事件的話,padding區域會響應,而margin區域不會響應。
  • color:用來設置container背景色,如果foregroundDecoration設置的話,可能會遮蓋color效果。
  • decoration:Decoration是對Container進行裝飾的描述。其概念類似與android中的shape。一般實際場景中會使用他的子類BoxDecoration。BoxDecoration提供了對背景色,邊框,圓角,陰影和漸變等功能的定制能力。注意設置了decoration,就不能設置color屬性,否則會報錯,此時應該在decoration中進行顏色的設置。
  • foregroundDecoration:繪制在child前面的裝飾。
  • width:container的寬度,設置為double.infinity可以強制在寬度上撐滿,不設置,則根據child和父節點兩者一起布局。
  • height:container的高度,設置為double.infinity可以強制在高度上撐滿。
  • constraints:添加到child上額外的約束條件。
  • margin:圍繞在decoration和child之外的空白區域,不屬于內容區域。
  • transform:設置container的變換矩陣,類型為Matrix4。
  • child:container中的內容widget。
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: 'container',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('container'),
        ),
        body: Container(
          child: Text('xhhsasasashs'),
          height: 400.0,
          alignment: Alignment.bottomCenter,
//          color: Colors.redAccent,
          padding: EdgeInsets.all(20.0),
          margin: EdgeInsets.all(12.0),
          decoration: BoxDecoration(
            border: Border.all(
                color: Color(0xffff2200), width: 8.0, style: BorderStyle.solid
            ),
            color: Colors.grey,
            borderRadius: BorderRadius.all(Radius.circular(20)),
            image: new DecorationImage(
              image: NetworkImage('https://www.baidu.com/img/bd_logo1.png'),
              fit: BoxFit.fitWidth
            ),
          ),
          constraints: BoxConstraints(
            maxHeight: 500.0
          )
        ),
      ),
    );
  }
}

2.Text

Text 控件是用來顯示一段文本的

  • style:設置文本的樣式,要求TextStyle類型,可以設置字體顏色、大小、字間距等等。
const TextStyle({
    this.inherit: true,         // 為false的時候不顯示
    this.color,                    // 顏色 
    this.fontSize,               // 字號
    this.fontWeight,           // 繪制文本時使用的字體粗細,加粗也用這個字段 
    this.fontStyle,                // FontStyle.normal  FontStyle.italic斜體
    this.letterSpacing,        // 字符間距  就是單個字母或者漢字之間的間隔,可以是負數
    this.wordSpacing,        // 字間距 句字之間的間距
    this.textBaseline,        // 基線,兩個值,字面意思是一個用來排字母的,一人用來排表意字的(類似中文)
    this.height,                // 當用來Text控件上時,行高(會乘以fontSize,所以不以設置過大)
    this.decoration,        // 添加上劃線,下劃線,刪除線 
    this.decorationColor,    // 劃線的顏色
    this.decorationStyle,    // 這個style可能控制畫實線,虛線,兩條線,點, 波浪線等
    this.debugLabel,
    String fontFamily,    // 字體
    String package,
  }) : fontFamily = package == null ? fontFamily : 'packages/$package/$fontFamily',
       assert(inherit != null);
  • textAlign:對齊方式
  • textDirection:跟textAlign相似,TextDirection.ltr文本從左到右
  • softWrap:是否需要換行。默認為true
  • overflow:超出文本處理,clip 裁剪,ellipsis 顯示省略號,fade 文本淡化
  • maxLines:最大行數
RichText

RichText:Text 只能顯示一種樣式的文字,如果你想在一段文字中顯示多種樣式的話 ,就需要使用 RichText 了。

RichText(
  text: TextSpan(
    text: 'Hello ',
    style: DefaultTextStyle.of(context).style,
    children: <TextSpan>[
      TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
      TextSpan(text: ' world!'),
    ],
  ),
)

3.Image

  • Image:通過ImageProvider來加載圖片
  • Image.asset:用來加載本地資源圖片
  • Image.file:用來加載本地(File文件)圖片
  • Image.network:用來加載網絡圖片
  • Image.memory:用來加載Uint8List資源(byte數組)圖片

圖片格式上支持: JPEG , PNG ,GIF , 動態 GIF , WebP , 動態WebP , BMP WBMP .

  • width & height
    用來指定顯示圖片區域的寬高(并非圖片的寬高)
  • fit
    設置圖片填充,類似于Android中的ScaleType
    • BoxFit.none
      原始大小居中
    • BoxFit.contain
      包含,不改變原有比例讓容器包含整個圖片,容器多余部分填充背景
    • BoxFit.cover
      覆蓋,不改變原有比例,讓圖片充滿整個容器,圖片多余部分裁剪
    • BoxFit.fill
      填充,忽略原有的寬高比,填滿為止
    • BoxFit.fitHeight
      縱向圖片填充
    • BoxFit.fitWidth
      橫向圖片填充
    • BoxFit.scaleDown
      圖片大小小于容器事相當于none,圖片大小大于容器時縮小圖片大小實現contain
  • color & colorBlendMode
    這兩個屬性需要配合使用,就是顏色和圖片混合,就類似于Android中的Xfermode,一般少用到
  • alignment
    用來控制圖片擺放的位置
  • repeat
    用來設置圖片重復顯示(repeat-x水平重復,repeat-y垂直重復,repeat兩個方向都重復,no-repeat默認情況不重復),就是填充view時候的不同方式。
  • centerSlice
    設置圖片內部拉伸,相當于在圖片內部設置了一個.9圖,但是需要注意的是,要在顯示圖片的大小大于原圖的情況下才可以使用這個屬性,要不然會報錯.理由是下面這個源碼:
    assert(sourceSize == inputSize, 'centerSlice was used with a BoxFit that does not guarantee that the image is fully visible.');
  • matchTextDirection
    這個需要配合Directionality進行使用
  • gaplessPlayback
    當圖片發生改變之后,重新加載圖片過程中的樣式
例子
import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:typed_data';

import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';

void main() => runApp(MyApp());

//assets/images/tzd.jpg
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
//    debugPaintSizeEnabled = true;
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Image demo'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              //加載網絡圖片
              Image.network(
                'https://www.baidu.com/img/bd_logo1.png?where=super',
                width: 100.0,
                height: 100.0,
              ),

              //加載Assets
              Image.asset(
                'assets/images/tzd.jpg',
                width: 200.0,
                height: 200.0,
              ),

              //Memory
              MemoryImageWidget(),

              //從文件加載圖片
              FileImageWidget(),
            ],
          ),
        ),
      ),
    );
  }
}

class FileImageWidget extends StatefulWidget {
  @override
  _FileImageWidgetState createState() => _FileImageWidgetState();
}

class _FileImageWidgetState extends State<FileImageWidget> {
  File _image;

  Future getImge() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image = image;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Center(
          child: _image == null
              ? Text('未選擇圖片!')
              : Image.file(
                  _image,
                  width: 200.0,
                  height: 200.0,
                ),
        ),
        FlatButton(
          onPressed: getImge,
          child: Text(
            '選擇圖片',
            style: TextStyle(
              color: Color(0xff0000ff),
            ),
          ),
        ),
      ],
    );
  }
}

//stf StatefulWidget快捷鍵, stl StatelessWidget快捷鍵
class MemoryImageWidget extends StatefulWidget {
  @override
  _MemoryImageWidgetState createState() => _MemoryImageWidgetState();
}

class _MemoryImageWidgetState extends State<MemoryImageWidget> {
  Uint8List bytes;

  @override
  void initState() {
    super.initState();
    rootBundle.load('assets/images/tzd.jpg').then((data) {
      if (mounted) {
        setState(() {
          bytes = data.buffer.asUint8List();
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final _decoration = BoxDecoration(
      image: bytes == null ? null : DecorationImage(image: MemoryImage(bytes)),
    );
    return Container(
      width: 100.0,
      height: 100.0,
      decoration: _decoration,
    );
  }
}

4.Icon

圖標組件Icon展示圖標的組件,該組件不可交互,要實現交互圖標,可以考慮使用IconButton組件。圖標相關組件有以下幾個:

  • IconButton:可交互的Icon
  • Icons:框架自帶Icon集合
  • IconTheme:Icon主題
  • ImageIcon:通過AssetImages或者其他圖片顯示Icon
常用屬性
屬性名 類型 默認值 說明
color Color null 圖標的顏色,例如Colors.green[500]
icon IconData null 展示的具體圖標,可使用Icons圖標列表中的任意一個圖標即可,如Icons.phone表示一個電話的圖標
style TextStyle null 文本樣式,可定義文本的字體大小、顏色、粗細等
size Double 24.0 圖標的大小,注意需要帶上小數位
textDirection TextDirection TextDirection.ltr Icon組件里也可以添加文本內容。有些文本書寫的方向是從左到右,有些則是從右到左。從左到右使用TextDirection.ltr,從右到左使用TextDirection.rtl
IconButton

圖標按鈕組件IconButton是基于Meterial Design風格的組件,可以響應按下的事件,并且按下時帶水波紋效果。如果它的onPressed回調函數為null,那么這個按鈕處于禁用狀態,并且不可按下。

常用屬性
屬性名 類型 默認值 說明
alignment AlignmentGeometry Alignment.center 定義IconButton的Icon對齊方式,默認為居中。Alignment可以設置x,y的偏移量
icon Widget null 展示的具體圖標,可以使用Icons圖標列表中任意一個圖標即可,如Icons.phone表示一個電話圖標
color Color null 圖標組件的顏色
disabledColor Color ThemeData.disabledColor 圖標組件禁用狀態的顏色,默認為主題里的禁用顏色,也可以設置為其他顏色
iconSize double 24.0 圖標的大小,注意需要帶上小數點
onPressed VoidCallback null 當按鈕按下時會觸發此回調事件
tooltip String "" 當按鈕長按下時的提示語句
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 一、CSS入門 1、css選擇器 選擇器的作用是“用于確定(選定)要進行樣式設定的標簽(元素)”。 有若干種形式的...
    寵辱不驚丶歲月靜好閱讀 1,628評論 0 6
  • CSS 是什么 css(Cascading Style Sheets),層疊樣式表,選擇器{屬性:值;屬性:值}h...
    崔敏嫣閱讀 1,511評論 0 5
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML標準。 注意:講述HT...
    kismetajun閱讀 27,748評論 1 45
  • 選擇qi:是表達式 標簽選擇器 類選擇器 屬性選擇器 繼承屬性: color,font,text-align,li...
    love2013閱讀 2,339評論 0 11
  • HTML 5 HTML5概述 因特網上的信息是以網頁的形式展示給用戶的,因此網頁是網絡信息傳遞的載體。網頁文件是用...
    阿啊阿吖丁閱讀 4,080評論 0 0