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

Solution 1:

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