Flutter设置文字大小不随系统设置而改变

我们知道,在原生iOS开发中,一旦文字设置了font之后,是不会随着系统设置中的字体大小的改变而发生改变的。可是,在flutter开发中,我们使用的Text widget却会随着改变,这就会导致布局错乱,使得整个页面异常难看。

第一,如果是针对单独的Text widget,系统提供了textScaleFactor属性,用于设置文字的缩放倍率

Text(
    (model.reason) ,
   textScaleFactor: 1.0,
   maxLines: 1,
   overflow: TextOverflow.ellipsis,
   style: TextStyle(
      color: _isMine ? ColorResource.COLOR_FF7576 : ColorResource.COLOR_999999,
              fontSize: 12,
      ),
)

But,项目中要使用到那么多的Text,如果每个都添加这个属性的话,光是添加这个我就得秃了 o( ̄︶ ̄)o。 那有没有一劳永逸的办法呢?那必须是得有的!

实则也很简单,我们需要在入口文件main.dart文件中修改:

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Container(color: Colors.white),
      builder: (context, widget) {
        return MediaQuery(
          //设置文字大小不随系统设置改变
          data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
          child: widget,
        );
      },
    );
  }
}

我们通过在state的build函数中,builder属性设置MediaQuery的textScaleFactor固定为1.0,这样整个flutter项目中的文字的缩放率都变成了1.0,不会再随系统改变

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 共4条

请登录后发表评论