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;
}
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
You must ensure ScreenConfig.init() is called before you use ScreenConfig.screenWidth.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With