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

ScreenUtil初始化时自定义尺寸无效 #358

Closed luooyii closed 2 years ago

luooyii commented 2 years ago

在初始化的时候如果传了context,不管自定义尺寸是什么都没有意义。只有在context为空的情况下自定义尺寸才有效,但是context在定义的时候加了late,导致不传会报错。

  double get screenWidth =>
      context != null ? MediaQuery.of(context!).size.width : _screenWidth;

此外针对这个问题#353的一个建议,目前flutter针对desktop正式release,桌面端尺寸变化更为灵活,我目前同样遇到了需要计算多个size的情况。根据flutter_screenutil的思路写了一个方法临时在用。

static final Map<String, ScreenUtils> _map = {};

static void init(
    String key,
    BoxConstraints constraints, {
    Orientation orientation = Orientation.portrait,
    Size designSize = defaultSize,
    bool splitScreenMode = false,
    bool minTextAdapt = false,
  }) {
    ScreenUtils instance;
    if (_map.containsKey(key)) {
      instance = _map[key]!;
    } else {
      instance = ScreenUtils._();
      _map[key] = instance;
    }
    instance
      ..uiSize = designSize
      .._minTextAdapt = minTextAdapt
      .._orientation = orientation
      .._screenWidth = constraints.maxWidth
      .._screenHeight = splitScreenMode
          ? max(constraints.maxHeight, 700)
          : constraints.maxHeight;
  }
extension SizeExtension on num {
  ///[ScreenUtil.setWidth]
  double w(String key) => ScreenUtils.getInstance(key).setWidth(this);

  ///[ScreenUtil.setHeight]
  double h(String key) => ScreenUtils.getInstance(key).setHeight(this);

  ///[ScreenUtil.radius]
  double r(String key) => ScreenUtils.getInstance(key).radius(this);

  ///[ScreenUtil.setSp]
  double sp(String key) => ScreenUtils.getInstance(key).setSp(this);
}
lizhuoyuan commented 2 years ago

桌面还没太仔细弄过 有空优化一下 也可以提个pr

github-actions[bot] commented 2 years ago

This issue is stale because it has been open for 30 days with no activity.

github-actions[bot] commented 2 years ago

This issue was closed because it has been inactive for 14 days since being marked as stale.