【发布时间】:2020-12-10 10:27:34
【问题描述】:
我需要根据用户屏幕的宽度更改字体大小。为此,我使用了一个 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
...
════════════════════════════════════════════════════════════════════════════════
非常感谢您的帮助!
【问题讨论】:
-
为什么不使用 AutoSizeText 包?它如此快速高效,我可以轻松替换文本小部件。
-
我已经用文本小部件设计了它,我宁愿在重做之前看看是否有一个简单的解决方案可以解决我当前的问题。
-
AutoSizeText 就像用 AutoSizeText() 替换 Text() 一样简单。如果你真的不想用,没关系。
标签: flutter dart flutter-test