Flutter如何创建自适应文本小部件?

时间:2019-07-25 21:37:06

标签: text flutter responsive-design autosize

我在响应文本方面遇到问题。在我的应用中,文本字体大小不同,我需要对它们进行响应以适应不同的屏幕大小(仅手机和设备方向为纵向)。我还这样向textScaleFactor: 1.0添加了MaterialApp

    builder: (context, widget) {
      return MediaQuery(
        child: widget,
        data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      );
    },

但是并没有太大帮助。 我也尝试使用MediaQuery.of(context).size.width计算字体大小,但是我认为这是危险和错误的。我希望它尽可能地接近给我的设计,但是在此步骤中我开始迷失它。 有什么解决办法吗?您如何实现的?

谢谢。

7 个答案:

答案 0 :(得分:2)

您可以从 constraints 获取 LayoutBuilder 并将其传递给 ScreenUtil.init(),如下面的代码所示。

return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return OrientationBuilder(
          builder: (BuildContext context, Orientation orientation) {
            ScreenUtil.init(
              constraints,
              designSize: orientation == Orientation.portrait
                  ? (Platform.isAndroid || Platform.isIOS) ? Size(450.0, 870.0) : 
                    Size(705.0, 1366.0)
                  : (Platform.isAndroid || Platform.isIOS) ? Size(870.0, 450.0) : 
                    Size(1366.0, 705.0),
              allowFontScaling: false,
            );
            return MaterialApp(
              theme: ThemeData(
                textTheme: Theme.of(context).textTheme.copyWith(
                      headline6: TextStyle(
                        fontSize: 24.sp,
                      ),
                    ),
              ),
              home: HomeScreen(),
            );
          },
        );
      },
    );

我们可以勾选 orientation == Orientation.portrait 来设置我们正在设计的屏幕的宽度和高度。要支持两个方向,只需相应地反转宽度和高度值。

您还可以检查 Platform.isAndroid || Platform.isIOS 并提供移动设备的宽度和高度。

答案 1 :(得分:1)

您可以使用此插件flutter_screenutil。 这是一个用于调整屏幕和字体大小的flutter插件。让您的UI在不同的屏幕大小上显示合理的布局!

根据系统的“字体大小”可访问性选项初始化并设置合适的大小和字体大小以进行缩放 请在使用前设置设计图稿的宽度和高度,以及设计图稿的宽度和高度(单位px)。确保将页面设置在MaterialApp的主页中(即,输入文件,只需设置一次),以确保在每次使用之前设置合适的尺寸:

//fill in the screen size of the device in the design

//default value : width : 1080px , height:1920px , 
allowFontScaling:false
ScreenUtil.instance = ScreenUtil.getInstance()..init(context);

//If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.instance = ScreenUtil(width: 750, height: 
1334)..init(context);

//If you wang to set the font size is scaled according to the system's 
"font size" assist option
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, 
allowFontScaling: true)..init(context);

使用:# 适应屏幕尺寸: 传递设计草图的px大小:

适应屏幕宽度:ScreenUtil.getInstance()。setWidth(540),

适应屏幕高度:ScreenUtil.getInstance()。setHeight(200),

您还可以使用ScreenUtil()代替ScreenUtil.getInstance(),例如:ScreenUtil()。setHeight(200)

注意

高度也根据setWidth进行调整,以确保不变形(当您想要一个正方形时)

setHeight方法主要在高度上进行调整,您希望在显示相同的UIUsed时控制屏幕的高度和真实性。

//for example:
//rectangle
Container(
       width: ScreenUtil.getInstance().setWidth(375),
       height: ScreenUtil.getInstance().setHeight(200),
       ...
        ),

////If you want to display a square:
Container(
       width: ScreenUtil.getInstance().setWidth(300),
       height: ScreenUtil.getInstance().setWidth(300),
        ),

适配器字体:

//Incoming font size,the unit is pixel, fonts will not scale to 
respect Text Size accessibility settings
//(AllowallowFontScaling when initializing ScreenUtil)
ScreenUtil.getInstance().setSp(28)    

//Incoming font size,the unit is pixel,fonts will scale to respect Text 
Size accessibility settings
//(If somewhere does not follow the global allowFontScaling setting)
ScreenUtil(allowFontScaling: true).setSp(28)  

//for example:

Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
                'My font size is 24px on the design draft and will not change with the system.',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: ScreenUtil.getInstance().setSp(24),
                )),
            Text(
                'My font size is 24px on the design draft and will change with the system.',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: ScreenUtil(allowFontScaling: true).setSp(24),
                )),
          ],
        )

其他相关API:

ScreenUtil.pixelRatio       //Device pixel density
ScreenUtil.screenWidth      //Device width
ScreenUtil.screenHeight     //Device height
ScreenUtil.bottomBarHeight  //Bottom safe zone distance, suitable for buttons with full screen
ScreenUtil.statusBarHeight  //Status bar height , Notch will be higher Unit px
ScreenUtil.textScaleFactory //System font scaling factor

ScreenUtil.getInstance().scaleWidth //Ratio of actual width dp to design draft px
ScreenUtil.getInstance().scaleHeight //Ratio of actual height dp to design draft px

答案 2 :(得分:1)

class SizeConfig {
  static MediaQueryData _mediaQueryData;
  static double screenWidth;
  static double screenHeight;
  static double blockSizeHorizontal;
  static double blockSizeVertical;

  void init(BuildContext context) {
    _mediaQueryData = MediaQuery.of(context);
    screenWidth = _mediaQueryData.size.width;
    screenHeight = _mediaQueryData.size.height;
    blockSizeHorizontal = screenWidth / 100;
    blockSizeVertical = screenHeight / 100;
  }
}

SizeConfig().init(context);在小部件构建和使用后添加 style: TextStyle(fontSize: 2 * SizeConfig.blockSizeVertical,)

乘以所需的数字,至少尝试一次。我已附上屏幕截图。

我的解决方案:
My solution

其他解决方案:
Other Solutions

答案 3 :(得分:1)

尝试:您将根据不同的屏幕大小获得自适应文本大小

    class AdaptiveTextSize {
      const AdaptiveTextSize();

      getadaptiveTextSize(BuildContext context, dynamic value) {
    // 720 is medium screen height
        return (value / 720) * MediaQuery.of(context).size.height;
      }
    }

用例:

                 Text("Paras Arora",style: TextStyle(fontSize: 
                 AdaptiveTextSize().getadaptiveTextSize(context, 20)),

答案 4 :(得分:0)

您可以尝试以下方法:

final size = MediaQuery.of(context).size;

您可以对容器应用相同的概念,

Container(
            width: size.width * 0.85,
           ...
)

答案 5 :(得分:0)

我想回答我的问题。在过去的几个月中,我一直在使用flutter_screenutil

但是正如我在评论中提到的那样,我需要在主题中添加响应字体大小,因此我自定义了flutter_screenutil软件包以在其中使用它。我认为它工作完美。我已经在几个项目中使用了该解决方案,并且没有任何麻烦。

import 'package:flutter/material.dart';

class CustomScreenUtil {
  static CustomScreenUtil _instance;
  static const int defaultWidth = 1080;
  static const int defaultHeight = 1920;

  /// Size of the phone in UI Design , px
  num uiWidthPx;
  num uiHeightPx;

  /// allowFontScaling Specifies whether fonts should scale to respect Text Size accessibility settings. The default is false.
  bool allowFontScaling;

  static double _screenWidth;
  static double _screenHeight;
  static double _pixelRatio;
  static double _statusBarHeight;
  static double _bottomBarHeight;
  static double _textScaleFactor;

  CustomScreenUtil._();

  factory CustomScreenUtil() {
    return _instance;
  }

  static void init({num width = defaultWidth,
    num height = defaultHeight,
    bool allowFontScaling = false}) {
    if (_instance == null) {
      _instance = CustomScreenUtil._();
    }
    _instance.uiWidthPx = width;
    _instance.uiHeightPx = height;
    _instance.allowFontScaling = allowFontScaling;

    _pixelRatio = WidgetsBinding.instance.window.devicePixelRatio;
    _screenWidth = WidgetsBinding.instance.window.physicalSize.width;
    _screenHeight = WidgetsBinding.instance.window.physicalSize.height;
    _statusBarHeight = WidgetsBinding.instance.window.padding.top;
    _bottomBarHeight = WidgetsBinding.instance.window.padding.bottom;
    _textScaleFactor = WidgetsBinding.instance.window.textScaleFactor;
  }

  /// The number of font pixels for each logical pixel.
  static double get textScaleFactor => _textScaleFactor;

  /// The size of the media in logical pixels (e.g, the size of the screen).
  static double get pixelRatio => _pixelRatio;

  /// The horizontal extent of this size.
  static double get screenWidthDp => _screenWidth;

  ///The vertical extent of this size. dp
  static double get screenHeightDp => _screenHeight;

  /// The vertical extent of this size. px
  static double get screenWidth => _screenWidth * _pixelRatio;

  /// The vertical extent of this size. px
  static double get screenHeight => _screenHeight * _pixelRatio;

  /// The offset from the top
  static double get statusBarHeight => _statusBarHeight;

  /// The offset from the bottom.
  static double get bottomBarHeight => _bottomBarHeight;

  /// The ratio of the actual dp to the design draft px
  double get scaleWidth => _screenWidth / uiWidthPx;

  double get scaleHeight => _screenHeight / uiHeightPx;

  double get scaleText => scaleWidth;

  /// Adapted to the device width of the UI Design.
  /// Height can also be adapted according to this to ensure no deformation ,
  /// if you want a square
  num setWidth(num width) => width * scaleWidth;

  /// Highly adaptable to the device according to UI Design
  /// It is recommended to use this method to achieve a high degree of adaptation
  /// when it is found that one screen in the UI design
  /// does not match the current style effect, or if there is a difference in shape.
  num setHeight(num height) => height * scaleHeight;

  ///Font size adaptation method
  ///@param [fontSize] The size of the font on the UI design, in px.
  ///@param [allowFontScaling]
  num setSp(num fontSize, {bool allowFontScalingSelf}) =>
      allowFontScalingSelf == null
          ? (allowFontScaling
          ? (fontSize * scaleText)
          : ((fontSize * scaleText) / _textScaleFactor))
          : (allowFontScalingSelf
          ? (fontSize * scaleText)
          : ((fontSize * scaleText) / _textScaleFactor));
}

现在,屏幕工具使用的是WidgetsBinding.instance.window中的尺寸,而不是MediaQuery中的尺寸,现在我们可以在没有上下文的情况下使用它了:

_screenUtil = CustomScreenUtil();
ThemeData(
        primaryTextTheme: TextTheme(
          bodyText1: TextStyle(
            fontSize: _screenUtil.setSp(12),
          )
        ))

我不知道这是否是最好的解决方案,但我正在这样工作

答案 6 :(得分:0)

LayoutBuilder(
builder:(context,constraints){
return Text("this is responsive text",
   style:TextStyle
(fontSize:constraints.maxWidth*the percentage of your text));
//("this is how to calculate //    percentage of fontsize"
//    e.g "fontSize/total Width*100" then for example i recived the percentage on // 
//  calculator"3.45" then multiply the maxWidth with 0.0345)
   }
  );


)