如何使用flutter_screenutil缩放字体与设备大小



我无法在更大的屏幕上放大字体。无论设备大小如何,字体大小保持不变。我该如何做到这一点?

这是我的MaterialApp代码;

ScreenUtilInit(
designSize: Size(412, 869),
builder: () => MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Progressive Institute Events',
theme: ThemeData(
primarySwatch: Colors.blue,
textTheme: TextTheme(
bodyText1: TextStyle(fontSize: 16.sp),
bodyText2: TextStyle(fontSize: 16.sp),
),
),
home: _runIntroSlider
? IntroScreen(
disableIntroScreen: _disableIntroScreen,
)
: auth.isAuth
? HomeScreen()
: FutureBuilder(
future: auth.tryAutoLogin(),
builder: (ctx, authResultSnapshot) =>
authResultSnapshot.connectionState ==
ConnectionState.waiting
? Center(child: CircularProgressIndicator())
: AuthScreen(),
),
routes: {
TabsScreen.routeName: (ctx) => TabsScreen(),
SponsorDetailsScreen.routeName: (ctx) => SponsorDetailsScreen(),
QuestionScreen.routeName: (ctx) => QuestionScreen(),
SendPushNotificationScreen.routeName: (ctx) =>
SendPushNotificationScreen(),
AboutAppScreen.routeName: (ctx) => AboutAppScreen(),
},
),
),

这是如何创建你自己的大小管理器。

按如下方法创建SizeManager类。(size_manager.dart)

class SizeManager {
static Orientation _orientation;
static DeviceType _deviceType;
static double _width;
static double _height;
void init(Size size, Orientation orientation) {
_orientation = orientation;
if (orientation == Orientation.portrait) {
_width = size.width;
_height = size.height;
} else {
_width = size.height;
_height = size.width;
}
//for mobile and tablet screen
if (0 < _width && _width <= 310) {
_deviceType = DeviceType.SMobile;
} else if (310 < _width && _width <=600) {
_deviceType = DeviceType.Mobile;
} else {
_deviceType = DeviceType.Tablet;
}
}
static fs(var i) {
return _width / 100 * (i / 3);
}
static get orientation => _orientation;
static get deviceType => _deviceType;
}
enum DeviceType {
SMobile,
Mobile,
Tablet,
}
double getSize({double tabVal, double mobVal, double sMobVal}) {
switch (SizeManager.deviceType) {
case DeviceType.Tablet:
return tabVal;
break;
case DeviceType.Mobile:
return mobVal;
break;
case DeviceType.SMobile:
return sMobVal;
break;
default:
return mobVal;
}
}

然后创建扩展。(size_manager_extensions.dart)

extension SizeManagerExtensions on double {
double get fs => SizeManager.fs(this);
}

最后,你必须在OrientationBuilder的帮助下初始化SizeManager

return Scaffold(
body: OrientationBuilder(builder: (context, orientation) {
SizeManager().init(MediaQuery.of(context).size, orientation);
return Text(
'How to scale font size',
style: TextStyle(
//fontSize: 12.0.fs - this also works but you can controll it base on device size as below
fontSize:getSize(tabVal: 8.0.fs, mobVal: 12.0.fs, sMobVal: 16.0.fs),
color: Color(0xFF67AD5B),
fontWeight: FontWeight.w600),
);
}));

原来字体的大小主要是根据宽度和长度的最小值计算的,如果宽度和高度有轻微的变化,字体的大小调整可能很小。

我还注意到设置较小的设计尺寸效果更好。查看这个GitHUb线程。

最新更新