This is my size_config.dart file and I'm getting this error, don't know why.
I'm getting errors in every variable like
The non-nullable variable '_mediaQueryData' must be initialized.
The non-nullable variable 'screenWidth' must be initialized.
The non-nullable variable 'screenHeight' must be initialized.
The non-nullable variable 'defaultSize' must be initialized.
The non-nullable variable 'orientation' must be initialized.
import 'package:flutter/material.dart';
class SizeConfig {
static MediaQueryData _mediaQueryData; //error
static double screenWidth; //error
static double screenHeight; //error
static double defaultSize; //error
static Orientation orientation; //error
void init(BuildContext context){
_mediaQueryData = MediaQuery.of(context);
screenHeight = _mediaQueryData.size.height;
screenWidth = _mediaQueryData.size.width;
orientation = _mediaQueryData.orientation;
}
}
double getProportionateScreenHeight(double inputHeight){
double screenHeight = SizeConfig.screenHeight;
return (inputHeight / 812.0) * screenHeight;
}
double getProportionateScreenWidth(double inputWidth){
double screenWidth = SizeConfig.screenWidth;
return (inputWidth / 375.0) * screenWidth;
}
CodePudding user response:
You have two option.
1- You can close null-safety feature with environment sdk: ">=2.10.0 <3.0.0"
version in pubspec.yaml file.
2- Initialize all variables with late
keyword
CodePudding user response:
You can use the null check operator (?
or !
), here's official documentation of null safety.
import 'package:flutter/material.dart';
class SizeConfig {
static MediaQueryData? _mediaQueryData;
static double? screenWidth;
static double? screenHeight;
static double? defaultSize;
static Orientation? orientation;
void init(BuildContext context) {
_mediaQueryData = MediaQuery.of(context);
screenHeight = _mediaQueryData?.size.height;
screenWidth = _mediaQueryData?.size.width;
orientation = _mediaQueryData?.orientation;
}
}
double getProportionateScreenHeight(double inputHeight) {
double? screenHeight = SizeConfig.screenHeight;
return (inputHeight / 812.0) * screenHeight!;
}
double getProportionateScreenWidth(double inputWidth) {
double? screenWidth = SizeConfig.screenWidth;
return (inputWidth / 375.0) * screenWidth!;
}
CodePudding user response:
import 'package:flutter/material.dart';
class SizeConfig {
static MediaQueryData _mediaQueryData;
late double screenWidth;
late double screenHeight;
late double defaultSize;
late Orientation orientation;
void init(BuildContext context) {
_mediaQueryData = MediaQuery.of(context);
screenHeight = _mediaQueryData?.size.height;
screenWidth = _mediaQueryData?.size.width;
orientation = _mediaQueryData?.orientation;
}
}
double getProportionateScreenHeight(double inputHeight) {
double? screenHeight = SizeConfig.screenHeight;
return (inputHeight / 812.0) * screenHeight!;
}
double getProportionateScreenWidth(double inputWidth) {
double? screenWidth = SizeConfig.screenWidth;
return (inputWidth / 375.0) * screenWidth!;
}