在ThemeData中指定FontSize时,如何根据ScreenWidth来实现动态字体大小?

问题描述

我需要根据用户屏幕的宽度来更改字体大小。为此,我正在使用一个文件size_config.dart,其中包含getProportionateScreenWidth()方法来检索用户屏幕宽度并进行一些计算。

因为我要使用浅色和深色UI,所以我正在创建两个ThemeData类,并决定在其中进行所有TextStyles。我现在的问题是,当我尝试调用该方法来设置字体大小时,出现了NoSuchMethodError:在null上调用了“ toDouble”方法。大概是因为ThemeData是在应用启动之前计算的?因此,没有可用的屏幕宽度,因此出现错误。有一个简单的解决方法吗?

//size_config.dart
class SizeConfig {
  static MediaQueryData _mediaQueryData;
  static double screenWidth;
  static double screenHeight;
  static double defaultSize;
  static Orientation orientation;

  void init(BuildContext context) {
    _mediaQueryData = MediaQuery.of(context);
    screenWidth = _mediaQueryData.size.width;
    screenHeight = _mediaQueryData.size.height;
    orientation = _mediaQueryData.orientation;
  }
}

double getProportionateScreenWidth(double inputWidth) {
  double screenWidth = SizeConfig.screenWidth;
  // 375 is the layout width that designer use
  return (inputWidth / 375.0) * screenWidth;
}
//themes.dart
ThemeData lightTheme() {
  return ThemeData (
    textTheme: lightTextTheme()
    //and other theme stuff
  );
}

TextTheme textTheme() {
  return TextTheme(
      headline1: TextStyle(
          color: Color(0xFF000000),fontSize: getProportionateScreenWidth(25),//problem is with here i believe
          fontWeight: FontWeight.normal),);
}
//main.dart
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',theme: lightTheme(),//instantiating theme
      initialRoute: '/onboarding',routes: {
        '/onboarding': (context) => OnboardingScreen(),'/home': (context) => HomeScreen(),'/assistant': (context) => AssistantScreen(),},);
  }
}
//body.dart (where headline1 is being used) don't believe problem is here as this is not even rendered in upon start of the app (an onBoarding screen comes before it named routing is used to navigate the separate screens)
Text(
  'Hello,',textAlign: TextAlign.left,style: Theme.of(context).textTheme.headline1,),
//Error message
════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building MyApp(dirty):
The method 'toDouble' was called on null.
Receiver: null
Tried calling: toDouble()

The relevant error-causing widget was
    MyApp 
package:dash/main.dart:17
When the exception was thrown,this was the stack
#0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:51:5)
#1      double.*  (dart:core-patch/double.dart:36:23)
#2      getProportionateScreenWidth 
package:dash/size_config.dart:29
#3      textTheme 
package:dash/themes.dart:35
#4      lightTheme 
package:dash/themes.dart:11
...
════════════════════════════════════════════════════════════════════════════════

非常感谢您的帮助!

解决方法

为此,我使用媒体查询。使用MediaQuery.of(context).size.height / 100 * 5,我首先将设备高度转换为百分比,然后乘以某个数字。您也可以这样做,并且可以为尺寸创建一个单独的类。我的标注类看起来像这样。

class Dimensions {
  static double boxWidth;
  static double boxHeight;

  Dimensions(context) {
    boxHeight = MediaQuery.of(context).size.height / 100;
    boxWidth = MediaQuery.of(context).size.width / 100;
  }
}

然后我可以调用Dimensions.box height *(设置某人)来设置任何动态变化的约束,但是请记住在任何构建方法之前都要初始化此维度类。
就像下面一样。

  @override
  Widget build(BuildContext context) {
    Dimensions(context);   //initializing context
    return Material(
      child: Center(
        child: Text(
          "This is Splash Screen",style: TextStyle(fontSize: Dimensions.boxHeight * 5),//Using dynamic sizing.
        ),),);
  }
,

您还可以检查此软件包flutter_screenutil

用于调整屏幕和字体大小的Flutter插件。保证在不同型号上看起来都不错

用于调整屏幕和字体大小的flutter插件。让您的UI在不同的屏幕大小上显示合理的布局!

他们仍在不断开发它,并且非常易于使用。

,
//main.dart
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
   
     SizeConfig().init(context); // add this line for initialization

    return MaterialApp(
      title: 'Flutter Demo',theme: lightTheme(),//instantiating theme
      initialRoute: '/onboarding',routes: {
        '/onboarding': (context) => OnboardingScreen(),'/home': (context) => HomeScreen(),'/assistant': (context) => AssistantScreen(),},);
  }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...