class Variables {
double screenWidth;
double screenHeight;
Variables() {
screenWidth = 0;
screenHeight = 0;
}
void defaultVariables(double width, double height) {
screenWidth = width;
screenHeight = height;
}
}
Variables variables = Variables();
The variables cannot be accessed through variable constructor
CodePudding user response:
You are failing to initialize the variables in time.
As has been pointed out, a non-nullable instance variable must be initialized during object initialization, before any code has access to the constructed object and can potentially read the variable in an uninitialized state.
The constructor body does not work for this, since it's only executed after the object has been fully created - the constructor body can access this
, so the variable must be initialized before that.
The assignments in the constructor body are just normal assignments, not initializations (unlike a language like Java).
Instead Dart allows you to initialize instance variables in one of three ways:
- Initializer expression on the variable (
int foo = valueExpression;
), - Intializing formal parameter (
this.foo
as a parameter), or - Initializer list assignment (
: foo = valueExpression , ... {}
).
The initializing formal only works to initialize using the value of an argument to the constructor, which is not what you need here.
So, you can define your class as:
class Variables {
double screenWidth = 0; // initializer expression.
double screenHeight;
Variables() : screenHeight = 0; // initializer list assignment.
// ...
}
(In practice you'd use the same approach for both variables, here I'm just showing them both.)
Or, as an alternative, you can use optional initializing formals with default values instead:
class Variables {
double width;
double height;
Variables({this.width = 0, this.height = 0});
...
}
Either approach ensures the variables are initialized in a timely manner and allows you to keep them non-nullable, so you don't have to check for null
when reading the variables.
CodePudding user response:
Check out Dart Sound null safety, there are plenty of good articles about it.
https://dart.dev/null-safety/understanding-null-safety
https://codewithandrea.com/videos/dart-null-safety-ultimate-guide-non-nullable-types/
Otherwise, try this!
double? screenWidth;
double? screenHeight;