Reputation: 1248
I used this code for responsiveness in my UI. So what this code basically does is calculate the size of the screen and I use the functions below to put the exact font size according to the design provided to me in Figma or Adobe XD. Using this method, I was able to create pixel-perfect UI.
After upgrading to Flutter 2.0.3
, I am getting null safety errors. I was able to solve most of them but I am not able to solve this error.
Please advice.
Complete Code
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);
screenWidth = _mediaQueryData!.size.width;
screenHeight = _mediaQueryData!.size.height;
orientation = _mediaQueryData!.orientation;
if (orientation == Orientation.landscape) {
defaultSize = screenHeight! * 0.024;
} else {
defaultSize = screenWidth! * 0.024;
}
}
}
double getSize(double size) {
var defaultsSize = SizeConfig.defaultSize * size;
return (defaultsSize / 10);
}
// 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 width as per screen size
double getProportionateScreenWidth(double inputWidth) {
double screenWidth = SizeConfig.screenWidth!;
// 375 is the layout width that Figma provides
return (inputWidth / 375.0) * screenWidth;
}
Error
Upvotes: 2
Views: 4786
Reputation: 602
You have three options:
int? count = 1;
void main() {
// will throw an error if count is null
print(count! * 2);
}
int? count = 1;
void main() {
// safe
print((count ?? 1) * 2);
}
int? count = 1;
void main() {
if(count != null) {
print(count! * 2);
} else {
print('count is null');
}
}
Upvotes: 2
Reputation: 267684
Problem:
You get this error because the object you're invoking *
on can be null
.
Example:
int? count = 1;
void main() {
print(count * 2); // error: The operator '*' can't be unconditionally invoked ...
}
Solutions:
Use a local variable:
int? count = 1;
void main() {
var i = count;
if (i != null) {
print(i * 2); // Prints 2
}
}
Use bang operator (!
)
int? count = 1;
void main() {
print(count! * 2); // Prints 2
}
Upvotes: 3
Reputation: 2490
Because SizeConfig.defaultSize
is nullable, you need to make sure that its value should not be null.
You can add some assertion to notify the caller that SizeConfig
should be initialized first. Then, you can change it to SizeConfig.defaultSize!
.
Sample...
double getSize(double size) {
assert(
SizeConfig.defaultSize != null,
"SizeConfig should be initialized (only once) before calling getSize(...). Refer to SizeConfig.init(...).",
);
var defaultsSize = SizeConfig.defaultSize! * size;
return (defaultsSize / 10);
}
Upvotes: 4