首页 > 解决方案 > ThemeData中指定FontSize时如何根据ScreenWidth做动态字体大小?

问题描述

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

因为我想要一个明暗的 UI,所以我创建了两个 ThemeData 类,并决定在其中执行所有 TextStyles。我现在的问题是,当我尝试调用该方法来设置字体大小时,我得到一个 NoSuchMethodError: The method 'toDouble' was called on null。想必是因为 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
...
════════════════════════════════════════════════════════════════════════════════

非常感谢您的帮助!

标签: flutterdartflutter-test

解决方案


我为此使用媒体查询使用 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.
        ),
      ),
    );
  }

推荐阅读