flutter 有没有办法在初始抖动时访问屏幕的高度和宽度?

jhdbpxl9  于 2022-12-05  发布在  Flutter
关注(0)|答案(3)|浏览(97)

我正在尝试预加载我的图像并在初始化状态下声明一次

范例:

late List<String> _assetBg;
  late List<Image> _imagesBg;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _assetBg = ['assets/images/1.jpg',
      'assets/images/2.jpg',
      'assets/images/3.jpg',
      'assets/images/4.jpg'];

    _imagesBg = _initializeListImage(context, _assetBg);
          
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      _tombolRenderBox =
          _tombolKey.currentContext!.findRenderObject() as RenderBox;
    });
  }

问题是:

List<Image> _initializeListImage (BuildContext context,List<String> assets){
    List<Image> result = [];
    for (var asset in assets) {
      result.add(
          Image(
            image: AssetImage(asset),
            ///Problem is here :
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width * 2,
            fit: BoxFit.cover,

          )
      );
    }
    return result;
  }

并在此处预加载:

@override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _prechaceImage(context, _imagesBg);
  }

void _prechaceImage(BuildContext context, List<Image> images){
    for(var image in images){
      precacheImage(image.image, context);
    }
  }

但这给了我一个错误

错误:

dependOnInheritedWidgetOfExactType<MediaQuery>() or dependOnInheritedElement() was called before _IntroScreenState.initState() completed.
有办法解决这个问题吗?我真的需要计算屏幕宽度来动画旋转我的小部件,谢谢帮助。

dsekswqp

dsekswqp1#

您可以使用dart:ui包中的window

import 'dart:ui';

// Screen size in density independent pixels
var screenWidth = (window.physicalSize.shortestSide / window.devicePixelRatio);
var screenHeight = (window.physicalSize.longestSide / window.devicePixelRatio);

// Screen size in real pixels
var screenWidthPixels = window.physicalSize.shortestSide;
var screenHeightPixels = window.physicalSize.longestSide;

参考:https://api.flutter.dev/flutter/dart-ui/window.html

zazmityj

zazmityj2#

使用此方法,我们可以在没有上下文的情况下获取大小:

import 'dart:ui';

var pixelRatio = window.devicePixelRatio;

 //Size in physical pixels
var physicalScreenSize = window.physicalSize;
var physicalWidth = physicalScreenSize.width;
var physicalHeight = physicalScreenSize.height;

//Size in logical pixels
var logicalScreenSize = window.physicalSize / pixelRatio;
var logicalWidth = logicalScreenSize.width;
var logicalHeight = logicalScreenSize.height;
af7jpaap

af7jpaap3#

您可以在公共类中保存值

class ScreenSize {
   static double width;
   static double height;
}

而在闪屏或main.dart的构建方法中

ScreenSize.width = Mediaquery.of(context).size.width;
ScreenSize.height= Mediaquery.of(context).size.height;

你可以使用它的任何屏幕的应用程序,我希望这将是有帮助的

相关问题