Flutter 學習 - Widget 之 RichText

前言

我們在進行開發的時候經常會遇到一段文本中會有不同的字體,不同的顏色展示,在Android開發中我們會使用SpannableString或者Html.fronHtml來進行處理,那麼在Flutter中如何處理來做這樣的展示呢,Flutter爲我們提供了一個可以展示多中樣式的Widget - RichText

使用

首先先看下在最簡單的使用方法

          RichText(
              text: TextSpan(children: [
                TextSpan(
                    text: "我愛學習",
                    style: TextStyle(color: Colors.greenAccent, fontSize: 24)),
                TextSpan(
                    text: "我愛學習",
                    style: TextStyle(color: Colors.yellow, fontSize: 32)),
                TextSpan(
                    text: "我愛學習",
                    style: TextStyle(color: Colors.red, fontSize: 44),
                    semanticsLabel: "這是Flutter")
              ]),
            )

多種樣式展示之 - RichText

下面看下RichText的源碼

RichText({
    Key key, //Widget的標識
    @required this.text,//文字片段,類型 InlineSpan,通常我們會用TextSpan(它是InlineSpan的子類) 
    this.textAlign = TextAlign.start,//文本的對齊方式,類型 TextAlign
    this.textDirection,//文字方向,類型 TextDirection
    this.softWrap = true,//bool類型 是否支持軟換行符,false表示只有一行,水平無限延伸
    this.overflow = TextOverflow.clip,// 文字的截斷方式,類型TextOverflow
    this.textScaleFactor = 1.0,//double類型,代表相對於當前字體大小的縮放因子,默認值爲1.0
    this.maxLines,//int類型 顯示的最大行數	
    this.locale,//用於選擇用戶語言和格式設置首選項的標識符	 類型 Locale
    this.strutStyle,//使用的支柱風格  類型StrutStyle
    this.textWidthBasis = TextWidthBasis.parent,
  }) : assert(text != null),
       assert(textAlign != null),
       assert(softWrap != null),
       assert(overflow != null),
       assert(textScaleFactor != null),
       assert(maxLines == null || maxLines > 0),
       assert(textWidthBasis != null),
       super(key: key, children: _extractChildren(text));

注:RichText 中除了text 是必選的,其他的都是可選參數
下面着重看下TextSpan這個Widget,另外幾個在上一篇Flutter 學習 - Widget 之 Text中已進行詳細介紹,這裏不再贅述

  • TextAlign
  • TextDirection
  • TextOverflow
  • Locale
  • StrutStyle
  • TextSpan

TextSpan : 如果我們需要對一個Text內容的不同不分按照不同的樣式顯示,這時就可以使用TextSpan,它代表文本的一個片段,然後把不同的TextSpan組合起來

下面先看TextSpan的使用方法

TextSpan(
       text: "我愛學習",
       style: TextStyle(color: Colors.red, fontSize: 44)),

接下來看源碼

const TextSpan({
    this.text, //類型String ,要顯示的文字
    this.children,//子TextSpan 類型是List< TextSpan>
    TextStyle style,//文本樣式 類型是TextStyle
    this.recognizer,//一個手勢識別器,它將接收到達此文本範圍的事件,類型是GestureRecognizer
    this.semanticsLabel,//語義標籤,無實際用處,用於向Android上的TalkBack和iOS的VoiceOver提供圖像描述
  }) : super(style: style,);

注:Talkback是一款由谷歌官方開發的系統軟件,它的定位是幫助盲人或者視力有障礙的用戶提供語言輔助
Voiceover功能是蘋果公司在2009年4月新推出的一種語音輔助程序

結尾

截止到現在,RichText 就介紹完了。
以下是我的Flutter系列的鏈接,後續會持續更新,歡迎大家指正。

Flutter 系列文章

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章