Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LateInitializationError: Field 'screenWidth' has not been initialized. Exception in flutter

I am new to flutter I had this size config file and I used it in an old project and right now I took it again to another project and it shows no errors but when I run it gives me an Exception : ════════ Exception caught by widgets library ═══════════════════════════════════ The following LateError was thrown building Body(dirty): LateInitializationError: Field 'screenWidth' has not been initialized.

import 'package:flutter/material.dart';


class SizeConfig {
  static late MediaQueryData _mediaQueryData;
  static late double screenWidth;
  static late double screenHeight;
  static double? defaultSize;
  static Orientation? orientation;
  void init(BuildContext context) {
    _mediaQueryData = MediaQuery.of(context);
    screenWidth = _mediaQueryData.size.width;
    screenHeight = _mediaQueryData.size.height;
    orientation = _mediaQueryData.orientation;
  }
}
// Get the proportionate height as per screen size
double getProportionateScreenHeight(double inputHeight) {
  double screenHeight = SizeConfig.screenHeight;
  // 812 is the layout height that designer use
  return (inputHeight / 812.0) * screenHeight;
}
// Get the proportionate height as per screen size
double getProportionateScreenWidth(double inputWidth) {
  double screenWidth = SizeConfig.screenWidth;
  // 375 is the layout width that designer use
  return (inputWidth / 375.0) * screenWidth;
}
like image 954
Aly Samier Avatar asked Jun 09 '26 21:06

Aly Samier


2 Answers

make sure you call the method init() in build method

Widget build(BuildContext context) {
SizeConfig().init(context);}

and make sure you import sizeconfig class from the right source for example :

import 'package:to_app/ui/size_config.dart';

where you want to use it

like image 150
bahmed hakimi Avatar answered Jun 12 '26 11:06

bahmed hakimi


You must ensure ScreenConfig.init() is called before you use ScreenConfig.screenWidth.

like image 25
聂超群 Avatar answered Jun 12 '26 12:06

聂超群



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!