Home > front end >  is there a way to access the screen height and width in initstate flutter?
is there a way to access the screen height and width in initstate flutter?

Time:01-18

I am trying to preload my images and declare once in 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;
    });
  }

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);
    }
  }

this one give me 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 witdh to animate rotation of my widget, thanks for help

CodePudding user response:

You can save value in common class

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

And in build method of splash screen or main.dart

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

You can use it any screen of app, I hope this will be helpful

CodePudding user response:

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

  •  Tags:  
  • Related