OpenFlutter / flutter_screenutil

Flutter screen adaptation, font adaptation, get screen information
https://pub.dartlang.org/packages/flutter_screenutil
Apache License 2.0
3.88k stars 494 forks source link

变量和静态变量定义的值,无法在旋转时进行更新 #379

Closed MrChen2016-08-27 closed 2 years ago

MrChen2016-08-27 commented 2 years ago

我在一个common.dart 设置了一个全局样式类,类似如下:

class CommonStyle{ static final TextStyle defaultTextStyle = new TextStyle(  fontSize: ScreenUtil().setSp(14),  color: new Color.fromARGB(255, 0, 0, 0) ); static final TextStyle defaultButtonTextStyle = new TextStyle(  fontSize: ScreenUtil().setSp(14),  color: new Color.fromARGB(255, 0, 0, 0) ); static final TextStyle inputTextStyle = new TextStyle(  fontSize: ScreenUtil().setSp(14) );

然而,我在旋转屏幕时,发现打印CommonStyle.defaultTextStyle.fontSize该值并没有被修改,依然是打开时初始化方向的值。 但是直接在 build 函数打印或者 20.sp,会根据旋转实时变化。

我直接尝试在 state 的 build外使用变量,发现依然存在这种情况:

double testSp = 20.sp; @override Widget build(BuildContext context) { // 是否是垂直方向  bool isVertical = Func.getDeviceIsPadAndVertical(context);  print(testSp.toString()); // ->33.333333333333336  print('#####${20.sp.toString()}'); // ->#####59.25925925925927  return isVertical ? renderPhoneBuild() : renderIpadBuild(); }

lizhuoyuan commented 2 years ago

字体的值现在是固定取适配中的最小值的 , 所以无论屏幕是否旋转字体大小都不会变化

Mounir-Bouaiche commented 2 years ago

ScreenUtil() 返回永远不会改变的值。 该库使用 InheritedElement 来通知更改,因此上下文的小部件及其所有后代将再次调用 build 方法以从 ScreenUtil() 获取新值。 您的代码基本上在构建方法之外声明 ScreenUtil().setSp() ,因此不会发生任何更改。 English: ScreenUtil() returns a value that will never change. The library uses InheritedElement to notify changes, so the context's widget and all its descendants will call the build method again to get the new values from ScreenUtil(). Your code basically declares ScreenUtil().setSp() outside of the build method, so nothing will change.