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

问题描述 投票:0回答:11

我遇到了响应文本的问题。在我的应用程序中有不同的文本字体大小,我需要使它们响应不同的屏幕尺寸(仅限手机和设备方向纵向)。我还将

textScaleFactor: 1.0
添加到我的
MaterialApp
中,如下所示:

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

但这并没有多大帮助。 我也尝试用

MediaQuery.of(context).size.width
来计算字体大小,但我认为这是危险且错误的。我希望它尽可能接近给我的设计,但在这些步骤中我开始失去它。

我该如何解决这个问题?

text flutter responsive-design autosize
11个回答
16
投票

我在开发适用于网络和移动设备的响应式应用程序时遇到了同样的问题,但是

textScaleFactor
帮助解决了我的问题,默认的textScaleFactor是
1
,所以我编写了一个根据屏幕宽度更改
textScaleFactor
的方法

import 'dart:math';
import 'package:flutter/material.dart';

class ScaleSize {
  static double textScaleFactor(BuildContext context, {double maxTextScaleFactor = 2}) {
    final width = MediaQuery.of(context).size.width;
    double val = (width / 1400) * maxTextScaleFactor;
    return max(1, min(val, maxTextScaleFactor));
  }
}

我们可以根据它的比例来控制尺寸版本, 在文本小部件中使用

Text(
     intro.subtitle,
     style: Theme.of(context).textTheme.subtitle1,
     textAlign: TextAlign.center,
     textScaleFactor: ScaleSize.textScaleFactor(context),
   ),


12
投票

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

根据系统的“字体大小”辅助选项初始化并设置适合大小和字体大小以进行缩放# 使用前请先设置好设计稿的宽度和高度,设计稿的宽度和高度(单位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(),例如: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

6
投票

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

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

5
投票
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,)
,

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

我的解决方案:

其他解决方案:


3
投票

你可以试试这个:

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

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

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

3
投票

您可以从

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
投票

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

现在 screen util 使用来自

WidgetsBinding.instance.window
的尺寸而不是来自
MediaQuery
的尺寸,现在我们可以在没有上下文的情况下使用它,如下所示:

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

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


1
投票

对于与应用程序的手机大小类似的字体大小:

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(设备的字体大小),

如果您需要比设备正常字体大小大的文本,则类似,

Text('aaaa' , textScaleFactor:2)


0
投票

1。第一个解决方案

您可以使用auto_size_text包

2。第二种解决方案

无需安装包即可解决问题,如果您更喜欢使用自定义主题:

获取宽度

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

在 theme_provider 类中创建您的自定义 ThemeData,即 for light 和 dark

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

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

-2
投票

这样做!

const Expanded(
    child: Text(
         "Your text.",
    overflow: TextOverflow.visible,
    maxLines: 5,
    softWrap: true,
    style: TextStyle(
    fontSize: 10,
    fontWeight: FontWeight.normal,
   ),
   textAlign: TextAlign.start,
 ),
),
© www.soinside.com 2019 - 2024. All rights reserved.