is there a way to access the screen height and width in initstate flutter?
384
You can use window
from dart:ui
package:
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;
Reference: https://api.flutter.dev/flutter/dart-ui/window.html
Author by
Sayyid J
Updated on January 03, 2023Comments
-
Sayyid J over 1 year
I am trying to preload my images and declare once in initstate
Example:
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; }); }
the problem is :
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; }
and prereload here :
@override void didChangeDependencies() { super.didChangeDependencies(); _prechaceImage(context, _imagesBg); } void _prechaceImage(BuildContext context, List<Image> images){ for(var image in images){ precacheImage(image.image, context); } }
But this gives me an error
error :
dependOnInheritedWidgetOfExactType<MediaQuery>() or dependOnInheritedElement() was called before _IntroScreenState.initState() completed.
is there a way to work around this? i really need to calculate screen width to animate rotation of my widget, thanks for help.
-
esentis over 2 yearsYou can try adding
_imagesBg = _initializeListImage(context, _assetBg);
insideaddPostFrameCallback
-
Sayyid J over 2 yearsthanks for your comment, if i put there give me another error :
LateInitializationError: Field '_imagesBg' has not been initialized.
. -
Alun Paranggi Wicaksono over 2 yearsis this the first screen? because if not, you can try to send the height and wight value from parameter
-
Sayyid J over 2 years@esentis i did your suggest assign
_listImages
with empty list, and initialize in post frame callback, its work, but if feel like hack somehow, thanks for your answer
-
-
luismiguelss almost 2 years
initState
runs beforebuild
, so you can't use it before assigning it