Flutter 在使用MaterialApp之前获取MediaQueryData 2

在使用 flutter_screenutil 这个插件的时候,需要注册

 ScreenUtil.init(context, width: 750, height: 1560, allowFontScaling: true);

这句话,需要放那里呢?一般情况下都是放到MaterialApp之后的HomePage上。

这样子就出现一个问题了。我需要在MaterialApp配置主题上就需要用到 flutter_screenutil 插件

ScreenUtil().setSp(getPrimaryTextSize())

所以必须需要将  ScreenUtil.init 放到MaterialApp之前。

代码如下:

void main() {
  runApp(MediaQueryFromWindow(
    child: ScreenApp(),
  ));
}

class MediaQueryFromWindow extends StatefulWidget {
  const MediaQueryFromWindow({
    Key key,
    @required this.child,
  }) : super(key: key);

  final Widget child;

  @override
  _MediaQueryFromWindowsState createState() => _MediaQueryFromWindowsState();
}

class _MediaQueryFromWindowsState extends State<MediaQueryFromWindow> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  // ACCESSIBILITY

  @override
  void didChangeAccessibilityFeatures() {
    setState(() {
      // The properties of window have changed. We use them in our build
      // function, so we need setState(), but we don't cache anything locally.
    });
  }

  // METRICS

  @override
  void didChangeMetrics() {
    setState(() {
      // The properties of window have changed. We use them in our build
      // function, so we need setState(), but we don't cache anything locally.
    });
  }

  @override
  void didChangeTextScaleFactor() {
    setState(() {
      // The textScaleFactor property of window has changed. We reference
      // window in our build function, so we need to call setState(), but
      // we don't need to cache anything locally.
    });
  }

  // RENDERING
  @override
  void didChangePlatformBrightness() {
    setState(() {
      // The platformBrightness property of window has changed. We reference
      // window in our build function, so we need to call setState(), but
      // we don't need to cache anything locally.
    });
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery(
      data: MediaQueryData.fromWindow(WidgetsBinding.instance.window),
      child: widget.child,
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}

class ScreenApp extends StatefulWidget {
  @override
  _ScreenAppState createState() => _ScreenAppState();
}

class _ScreenAppState extends State<ScreenApp> with WidgetsBindingObserver {
  @override
  Widget build(BuildContext context) {
    // 注册
    ScreenUtil.init(context, width: 750, height: 1560, allowFontScaling: true);
    return MyApp();
  }
}

 

posted @ 2020-03-31 14:36  柏。  阅读(887)  评论(0编辑  收藏  举报