Flutter Text詳解

示例

Simulator Screen Shot - iPhone 11 Pro Max - 2019-10-09 at 11.23.59

API

Text,很常用的一個Widget;用於顯示簡單樣式文本,它包含一些控制文本顯示樣式的一些屬性

text構造方法源碼:

/// If the [style] argument is null, the text will use the style from the
  /// closest enclosing [DefaultTextStyle].
  ///
  /// The [data] parameter must not be null.
  const Text(
    this.data, {
    Key key,
    this.style,
    this.strutStyle,
    this.textAlign,
    this.textDirection,
    this.locale,
    this.softWrap,
    this.overflow,
    this.textScaleFactor,
    this.maxLines,
    this.semanticsLabel,
    this.textWidthBasis,
  }) : assert(
         data != null,
         'A non-null String must be provided to a Text widget.',
       ),
       textSpan = null,
       super(key: key);

  /// Creates a text widget with a [InlineSpan].
  ///
  /// The following subclasses of [InlineSpan] may be used to build rich text:
  ///
  /// * [TextSpan]s define text and children [InlineSpan]s.
  /// * [WidgetSpan]s define embedded inline widgets.
  ///
  /// The [textSpan] parameter must not be null.
  ///
  /// See [RichText] which provides a lower-level way to draw text.
  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,
    this.textWidthBasis,
  }) : assert(
         textSpan != null,
         'A non-null TextSpan must be provided to a Text.rich widget.',
       ),
       data = null,
       super(key: key);

參數詳解:

data

要顯示的字符串

style樣式TextStyle

TextStyle的構造函數:

const TextStyle({
    this.inherit = true,
    this.color,
    this.backgroundColor,
    this.fontSize,
    this.fontWeight,
    this.fontStyle,
    this.letterSpacing,
    this.wordSpacing,
    this.textBaseline,
    this.height,
    this.locale,
    this.foreground,
    this.background,
    this.shadows,
    this.fontFeatures,
    this.decoration,
    this.decorationColor,
    this.decorationStyle,
    this.decorationThickness,
    this.debugLabel,
    String fontFamily,
    List<String> fontFamilyFallback,
    String package,
  }) : fontFamily = package == null ? fontFamily : 'packages/$package/$fontFamily',
       _fontFamilyFallback = fontFamilyFallback,
       _package = package,
       assert(inherit != null),
       assert(color == null || foreground == null, _kColorForegroundWarning),
       assert(backgroundColor == null || background == null, _kColorBackgroundWarning);
屬性 說明
inherit 是否將null值替換爲祖先文本樣式中的值(例如,在TextSpan樹中)。如果爲false,則沒有顯式值的屬性將恢復爲默認值:白色,字體大小爲10像素,採用無襯線字體。
color 字體顏色 如自定義顏色:Color.fromRGBO(155, 155, 155, 1) 也可以使用Colors類裏面自帶的屬性
backgroundColor 文本的背景顏色
fontSize 字體大小,默認14像素
fontWeight 字體厚度,可以使文本變粗或變細
FontWeight.bold 常用的字體重量比正常重。即w700
FontWeight.normal 默認字體粗細。即w400
FontWeight.w100 薄,最薄
FontWeight.w200 特輕
FontWeight.w300 輕
FontWeight.w400 正常/普通/平原
FontWeight.w500 較粗
FontWeight.w600 半粗體
FontWeight.w700 加粗
FontWeight.w800 特粗
FontWeight.w900 最粗
fontStyle 字體變體:
FontStyle.italic 使用斜體
FontStyle.normal 使用直立
letterSpacing 水平字母之間的空間間隔(邏輯像素爲單位)。可以使用負值來讓字母更接近。
wordSpacing 單詞之間添加的空間間隔(邏輯像素爲單位)。可以使用負值來使單詞更接近。
textBaseline 對齊文本的水平線:
TextBaseline.alphabetic:文本基線是標準的字母基線
TextBaseline.ideographic:文字基線是表意字基線;
如果字符本身超出了alphabetic 基線,那麼ideograhpic基線位置在字符本身的底部。
height 文本行與行的高度,作爲字體大小的倍數(取值1~2,如1.2)
locale 文本的前景色,不能與color共同設置(比文本顏色color區別在Paint功能多,後續會講解)
background 文本背景色Paint()…color = backgroundColor
foreground 文本的前景色,不能與color共同設置
shadows 文本的陰影可以利用列表疊加處理,例如shadows: [Shadow(color:Colors.black,offset: Offset(6, 3), blurRadius: 10)], color即陰影的顏色, offset即陰影相對文本的偏移座標,blurRadius即陰影的模糊程度,越小越清晰
decoration 文字的線性裝飾,比如 TextDecoration.underline 下劃線, TextDecoration.lineThrough刪除線
decorationColor 文本裝飾線的顏色
decorationStyle 文本裝飾線的樣式,比如 TextDecorationStyle.dashed 虛線

textAlign

文本應如何水平對齊enum:

可選值 說明
TextAlign.center 將文本對齊容器的中心。
TextAlign.end 對齊容器後緣上的文本。
TextAlign.start 對齊容器前緣上的文本。
TextAlign.justify 拉伸以結束的文本行以填充容器的寬度。即使用了decorationStyle才起效
TextAlign.left 對齊容器左邊緣的文本。
TextAlign.right 對齊容器右邊緣的文本。

textDirection

相對TextAlign中的start、end而言有用(當start使用了ltr相當於end使用了rtl,也相當於TextAlign使用了left)

可選值 說明
TextDirection.ltr ltr從左至右,
TextDirection.rtl rtl從右至左

softWrap

是否自動換行(true自動換行,false單行顯示,超出屏幕部分默認截斷處理)

overflow

文字超出屏幕之後的處理方式

可選值 說明
TextOverflow.clip 剪切溢出的文本以修復其容器。
TextOverflow.ellipsis 使用省略號表示文本已溢出。
TextOverflow.fade 將溢出的文本淡化爲透明。

其他

屬性 說明
textScaleFactor 字體顯示倍率
maxLines 文字顯示最大行數

文本拼接

在上面的例子中,Text的所有文本內容只能按同一種樣式,如果我們需要對一個Text內容的不同部分按照不同的樣式顯示,這時就可以使用TextSpan,它代表文本的一個“片段”。我們看看TextSpan的定義:

const TextSpan({
  TextStyle style, 
  Sting text,
  List<TextSpan> children,
  GestureRecognizer recognizer,
});

Demo源碼

import 'dart:math';

import 'package:flutter/material.dart';

class TextDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("文本測試"),
      ),
      backgroundColor: Colors.white,
      body: buildText(),
    );
  }
  Widget buildText(){
    return new SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Text('普通文本樣式'),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('自定義文本顏色',style: TextStyle(color: Color.fromRGBO(234,200,134,1)),),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本背景顏色',style: TextStyle(backgroundColor: Colors.red),),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本字體大小',style: TextStyle(fontSize: 30.0),),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本加粗',style: TextStyle(fontWeight: FontWeight.w900),),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本斜體',style: TextStyle(fontStyle: FontStyle.italic),),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本字母間隙space',style: TextStyle(letterSpacing: 2),),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本單詞間距 word space',style: TextStyle(wordSpacing: 10),),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本行高',style: TextStyle(height: 3, backgroundColor: Colors.red),),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本陰影shadows',style: TextStyle(shadows: [Shadow(color:Colors.black,offset: Offset(6, 3), blurRadius: 10)]),),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本文字刪除線',style: TextStyle(decoration: TextDecoration.lineThrough, decorationColor: Colors.red),),
            ),
            
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本文字底邊線',style: TextStyle(height: 3, decoration: TextDecoration.underline, decorationStyle: TextDecorationStyle.double),),
            ),
            
            Container(
              // margin: EdgeInsets.only(top: 50.0, left: 120.0), 
              constraints: BoxConstraints.tightFor(width: 200.0, height: 50.0), //卡片大小
              decoration: BoxDecoration(//背景裝飾
                  gradient: RadialGradient( //背景徑向漸變
                      colors: [Colors.red, Colors.orange],
                      center: Alignment.topLeft,
                      radius: .98
                  ),
                  boxShadow: [ //卡片陰影
                    BoxShadow(
                        color: Colors.black54,
                        offset: Offset(2.0, 2.0),
                        blurRadius: 4.0
                    )
                  ]
              ),
              // alignment: Alignment.center, 
              child: Text('文本對齊方式',textAlign: TextAlign.left,),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本換行測試softWrap(自動換行)文本換行測試(自動換行)文本換行測試(自動換行)文本換行測試(自動換行)文本換行測試(自動換行)', softWrap: true,),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本換行測試softWrap(不換行)文本換行測試(不換行)文本換行測試(不換行)文本換行測試(不換行)文本換行測試(不換行)', softWrap: false,),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本溢出測試overflow ellipsis文本溢出測試文本溢出測試文本溢出測試文本溢出測試文本溢出測試', overflow: TextOverflow.ellipsis,),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本溢出測試overflow clip文本溢出測試文本溢出測試文本溢出測試文本溢出測試文本溢出測試', overflow: TextOverflow.clip,),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本溢出測試overflow fade文本溢出測試文本溢出測試文本溢出測試文本溢出測試文本溢出測試', overflow: TextOverflow.fade,),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text('文本顯示行數2文本顯示行數2文本顯示行數2文本顯示行數2文本顯示行數2文本顯示行數2文本顯示行數2文本顯示行數2文本顯示行數2文本顯示行數2文本顯示行數2', maxLines: 2,),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text.rich(
                TextSpan(
                  children: [
                    TextSpan(
                    text:'¥',
                    style: TextStyle(
                      color: Color.fromRGBO(255,85,46,1),
                      fontSize: 18.0,
                      fontWeight: FontWeight.w700
                    )
                  ),
                  TextSpan(
                    text: '100',
                    style: TextStyle(
                      color: Color.fromRGBO(255,85,46,1),
                      fontSize: 24.0,
                      //字體加粗
                      fontWeight: FontWeight.w700
                    )
                  ),
                  TextSpan(
                    text:'1001元',
                    style: TextStyle(
                      decoration: TextDecoration.lineThrough,
                      color: Color.fromRGBO(153,153,153,1),
                      fontSize: 14.0,
                      //字體加粗
                      // fontWeight: FontWeight.w700
                    )
                  ),
                  TextSpan(
                    text:'拼接普通文本拼接普通文本拼接普通文本拼接普通文本拼接普通文本'
                  )
                  ]
                )
              ),
            ),
          ],
        ),
    );
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章