【问题标题】:How to get device font size in flutter如何在颤动中获取设备字体大小
【发布时间】:2020-03-02 13:36:05
【问题描述】:

当高度有界时,我遇到了列表视图的问题,所以当我更改手机字体大小时会发生溢出,我不想给容器额外的高度。

Container(
       height: fixed height goes here,
       child: ListView(
         scrollDirection: Axis.horizontal,
         children: <Widget>[
           some widgets goes here...
         ],
       ),
     )

【问题讨论】:

    标签: flutter


    【解决方案1】:

    你可以尝试依赖 textScaleFactor,默认是1.0 如果您在设备的设置页面上更改字体大小,此值将更改为 1.15 1.3 等等

    所以你可以将容器高度乘以这个值

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(),
            body: SafeArea(child: Home()),
          ),
        );
      }
    }
    
    class Home extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        double h = MediaQuery.of(context).textScaleFactor;
        return Center(
          child: Text('$h'), // with default settings it shows 1.0
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      如果您要查找设备字体大小(在智能手机的设置活动中设置),您可以使用MediaQuery 类的textScaleFactor 属性。

      double textScale = MediaQuery.of(context).textScaleFactor;
      

      或者,您可以像这样获得相同的值:

      double textScale = MediaQuery.textScaleFactorOf(context);
      

      请注意,Flutter 中的所有字体大小都会通过此设置自动缩放,因此如果用户将字体放大,您可能会遇到一些溢出错误。话虽如此,在调试时做同样的事情是找出布局可能溢出的好方法。

      查看 Flutter 文档的 accessibility section 了解更多信息。

      【讨论】:

        【解决方案3】:

        您需要检测屏幕高度并根据 tha 给出您的Container() 高度,并在build() 方法被重新调用时保持检测。

        这就是为您的Container() 获得响应高度的方法

        MediaQuery() 可以这样做,如下:

        Container(
               height: MediaQuery.of(context).size.height, // screen's size.height
               child: ListView(
                 scrollDirection: Axis.horizontal,
                 children: <Widget>[
                   some widgets goes here...
                 ],
               ),
             )
        

        Flutter 说的是 size 属性:

        以逻辑像素为单位的媒体大小(例如屏幕大小)。

        【讨论】:

        • 我想要的是容器完全采用其子项的高度而不是屏幕的高度,解决方案是使用 4 if else case,因为设备只有 4 种字体大小,但问题是我没有'不知道当前设备的字体大小
        猜你喜欢
        • 2019-09-21
        • 2013-06-18
        • 2018-12-19
        • 2016-06-18
        • 2013-04-09
        • 2015-09-09
        • 2014-10-09
        • 2018-12-27
        • 2022-12-21
        相关资源
        最近更新 更多