問題:
在Flutter中有一些場(chǎng)景會(huì)需要展示多格式的文本也就是富文本,這個(gè)時(shí)候我們可以使用RichText+TextSpan的方式來做展示。不過會(huì)發(fā)現(xiàn)iOS系統(tǒng)中如果設(shè)置字體顯示很大,這里的文本顯示就會(huì)很小。
先直接說解決方式:
用Text.rich來代替RichText
原因分析
問題的關(guān)鍵是textScaleFactor,代表字體縮放因子,是指每個(gè)邏輯像素對(duì)應(yīng)的實(shí)際字體像素,例如如果textScaleFactor這個(gè)值是1.5,那么字體將會(huì)比指定的字體大小大50%
在Text.rich的實(shí)現(xiàn)中,最終構(gòu)建widget仍然是RichText:
Widget result = RichText(
textAlign: textAlign ?? defaultTextStyle.textAlign ?? TextAlign.start,
textDirection: textDirection, // RichText uses Directionality.of to obtain a default if this is null.
locale: locale, // RichText uses Localizations.localeOf to obtain a default if this is null
softWrap: softWrap ?? defaultTextStyle.softWrap,
overflow: overflow ?? defaultTextStyle.overflow,
textScaleFactor: textScaleFactor ?? MediaQuery.textScaleFactorOf(context),
maxLines: maxLines ?? defaultTextStyle.maxLines,
strutStyle: strutStyle,
textWidthBasis: textWidthBasis ?? defaultTextStyle.textWidthBasis,
textHeightBehavior: textHeightBehavior ?? defaultTextStyle.textHeightBehavior ?? DefaultTextHeightBehavior.of(context),
text: TextSpan(
style: effectiveTextStyle,
text: data,
children: textSpan != null ? <InlineSpan>[textSpan] : null,
),
);
其中textScaleFactor是這樣實(shí)現(xiàn)的:
textScaleFactor: textScaleFactor ?? MediaQuery.textScaleFactorOf(context),
如果傳來的參數(shù)為空,則去用mediaQuery查詢獲得。
而直接使用RichText時(shí),默認(rèn)的textScaleFactor為1,不會(huì)隨著系統(tǒng)字體設(shè)置而變化。
RichText({
Key key,
@required this.text,
this.textAlign = TextAlign.start,
this.textDirection,
this.softWrap = true,
this.overflow = TextOverflow.clip,
this.textScaleFactor = 1.0,
this.maxLines,
this.locale,
this.strutStyle,
this.textWidthBasis = TextWidthBasis.parent,
this.textHeightBehavior,
})
總結(jié)
從Text.rich和RichText的構(gòu)造方式中也可以看出,Text.rich本身的實(shí)現(xiàn)也是調(diào)用RichText,不過有了更多默認(rèn)屬性的設(shè)置,這就給開發(fā)帶來一些便利,特別是可以覆蓋開發(fā)考慮不到的屬性,因此在實(shí)際開發(fā)中,需要在Flutter中使用富文本時(shí),開發(fā)中推薦使用Text.rich這種方式。