Flutter 如何创建响应式文本小部件?

Flutter how to create responsive Text widget?

我遇到了响应式文本的问题。在我的应用程序中有不同的文本字体大小,我需要让它们响应不同的屏幕尺寸(仅限手机和设备方向纵向)。我还像这样将 textScaleFactor: 1.0 添加到我的 MaterialApp 中:

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

但这并没有多大帮助。 我也尝试用 MediaQuery.of(context).size.width 计算字体大小,但我认为这很危险而且是错误的。我希望它尽可能接近给我的设计,但我开始在这个步骤上失去它。 有什么解决办法吗?你是如何做到这一点的?

提前致谢。

你可以试试这个:

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

您可以应用相同的概念,在本例中为容器:

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

你可以使用这个插件flutter_screenutil。 它是一个用于适配屏幕和字体的 flutter 插件 size.Let 您 UI 在不同的屏幕尺寸上显示合理的布局!

根据系统的 "font size" 辅助功能选项初始化并设置合适的大小和字体大小以进行缩放 # 使用前请设置好设计稿的宽高,设计稿的宽高(单位px)。一定要在MaterialApp的home中设置页面(即入口文件,只设置一次),确保每次使用前都设置好适合尺寸:

//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(),用于 example:ScreenUtil().setHeight(200)

备注

高度也根据setWidth进行适配,保证不变形(当你想要正方形的时候)

setHeight方法主要是在高度上进行适配,想要控制屏幕上的高度和实际显示时一样UI使用

//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
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,),

乘以你想要的次数,至少尝试一次。我附上了屏幕截图。

我的解决方案:

其他解决方案:

试试这个:你会根据不同的屏幕尺寸获得自适应文字大小

    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)),

我想回答我的问题。在过去的几个月里,我使用 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),
          )
        ))

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

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)
   }
  );


)

您可以从 LayoutBuilder 获取 constraints 并将其传递给 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并给出移动设备的宽度和高度。

这样做!

const Expanded(
    child: Text(
         "Your text.",
    overflow: TextOverflow.visible,
    maxLines: 5,
    softWrap: true,
    style: TextStyle(
    fontSize: 10,
    fontWeight: FontWeight.normal,
   ),
   textAlign: TextAlign.start,
 ),
),

1.第一个解决方案

您可以使用 auto_size_text package.

2。第二个解决方案

没有软件包的解决方法,如果您更喜欢使用自定义主题:

获取宽度

    @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
     return Container(...

创建您的自定义 ThemeData 即 您 theme_provider theme_provider class

的明暗
static ThemeData dark() {
return ThemeData(
  textTheme: const TextTheme(
   bodyText2:
        TextStyle(color: Colors.white70, fontWeight: FontWeight.w300)...

最后,为不同的屏幕使用不同的字体大小编辑您的文本小部件。您也可以使用屏幕高度...

Text( 
    widget.featuredModel.eventTitle,
    style: Theme.of(context).textTheme.bodyText2!
   .copyWith(  fontSize: width >= 1201
                          ? 22
                          : width >= 601
                              ? 20
                              : width >= 400
                                  ? 16
                                  : 14),
                ),

对于与 phone 应用大小相似的字体大小:

MaterialApp( home: MediaQuery(data:MediaQuery.of(context).copyWith(textScaleFactor: 1.2), child: HomePage()) );

对于ListTile_Subtitle:

Text('Your Text' , textScaleFactor:1.0)

注意:此处,普通文本中的 1.2 = 1.2 x (the_FontSize_of_device) & 对于 ListTile_Subtitle ,我们需要小于正常字体大小,所以,我们控制 它带有 Text Widget textScaleFactor 参数,在此处表示: 1x(the_FontSize_of_device),

如果您需要比设备的正常字体大小大的文本,则类似, Text('aaaa' , textScaleFactor:2)