我在我的 UI 中使用此代码来提高响应能力。所以这段代码基本上做的是计算屏幕的大小,我使用下面的函数根据 Figma 或 Adobe XD 中提供给我的设计来放置准确的字体大小。使用这种方法,我能够创建像素完美的 UI。
升级到 Flutter 2.0.3
后,出现空安全错误。我能够解决其中的大部分问题,但我无法解决此错误。
请指教。
完整代码
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;
}
错误
最佳答案
因为 SizeConfig.defaultSize
可以为 null,所以您需要确保它的值不应该为 null。
您可以添加一些断言来通知调用者应该首先初始化 SizeConfig
。然后,您可以将其更改为 SizeConfig.defaultSize!
。
示例...
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);
}
关于flutter - 运算符 '*' 不能无条件调用,因为接收者可以是 'null' 。尝试向目标 ('!' 添加空检查),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66986024/