Flutter一劳永逸解决Text字体 大致随 体系改变的 难题 flutter sleeve
Flutter提供的 Text Widget如果不设置 textScaleFactor 参数,在默认情况下会跟随 体系字体的变化而改变,textScaleFactor 变量的注释有详细的说明:
class Text extends StatelessWidget { ...... /// The number of font pixels for each logical pixel. /// /// For example, if the text scale factor is 1.5, text will be 50% larger than /// the specified font size. /// /// The value given to the constructor as textScaleFactor. If null, will /// use the [MediaQueryData.textScaleFactor] obtained from the ambient /// [MediaQuery], or 1.0 if there is no [MediaQuery] in scope. final double? textScaleFactor; ...... }
如果在项目中只有少数 几许 Text 需要固定 fontSize,在 Text 中设置 textScaleFactor 是很方便的。 然而 怎样项目中所有的 Text 的都要固定 fontSize ,可以参考 下面内容两个方案:
- 修改全局配置
- 自定义Text
方案一:修改全局配置
实现 MaterialApp 对象的 builder 参数,返回由 MediaQuery 包裹的Widget,通过 MediaQuery 的 data 参数设置全局的文字的 textScaleFactor 为 1.0 ,示例代码如下:
void in() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( ...... home: HomePage(), builder: (context, widget) { return MediaQuery( //设置全局的文字的textScaleFactor为1.0,文字不再随 体系设置改变 data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0), child: widget, ); }, ); } }
方案二:自定义Text
自定义 FixedSizeText 并继承 Text,在FixedSizeText的构造函数中设置textScaleFactor参数的默认值为1.0, 接着将这些参数通过super传给Text, 最后在布局Widget的时候使用FixedSizeText取代Text就可以了。 FixedSizeText的实现代码如下:
import package:flutter/ terial.dart ; import package:flutter_app2/View/FixedSizeText.dart ; class FixedSizeText extends Text { const FixedSizeText(String data, { Key key, TextStyle style, StrutStyle strutStyle, TextAlign textAlign, TextDirection textDirection, Locale locale, bool softWrap, TextOverflow overflow, double textScaleFactor = 1.0, int xLines, String se nticsLabel, }) : super(data, key:key, style:style, strutStyle:strutStyle, textAlign:textAlign, textDirection:textDirection, locale:locale, softWrap:softWrap, overflow:overflow, textScaleFactor:textScaleFactor, xLines: xLines, se nticsLabel:se nticsLabel); }