Home > OS >  LateInitializationError: Field 'screenWidth' has not been initialized
LateInitializationError: Field 'screenWidth' has not been initialized

Time:01-11

I am developing a mobile flutter application. I created a config myself to be able to use it on every page, but LateInitializationError: Field 'screenWidth' has not been initialized. I'm getting the error I need help.The question has been shared before, but there is no answer, so I wanted to ask it again.

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

static? double screenWidth; I did it like this, but this time I'm getting the Null check operator used on a null value error.

CodePudding user response:

Late fields must be initialized before use, in your case you might have forgotten to call the init method before accessing the fields. So, make sure to call the init method before accessing the fields in thae class SizeConfig.

  • Related