我正在尝试预加载我的图像并在 initstate 中声明一次
示例:
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.
有办法解决这个问题吗?我真的需要计算屏幕宽度来动画我的小部件的旋转,感谢您的帮助。
您可以使用
window
包中的 dart:ui
:
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;
window.physicalSize
已弃用,并将在未来版本中删除。
PlatformDispatcher
final view = PlatformDispatcher.instance.views.first;
print(view.physicalSize);
普通班可以省钱
class ScreenSize {
static double width;
static double height;
}
并在启动屏幕或main.dart的构建方法中
ScreenSize.width = Mediaquery.of(context).size.width;
ScreenSize.height= Mediaquery.of(context).size.height;
您可以在应用程序的任何屏幕上使用它,我希望这会有所帮助