flutter - 运算符 '*' 不能无条件调用,因为接收者可以是 'null' 。尝试向目标 (

我在我的 UI 中使用此代码来提高响应能力。所以这段代码基本上做的是计算屏幕的大小,我使用下面的函数根据 Figma 或 Adob​​e 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/

相关文章:

java - 使用 Java Streams 返回单词出现的句子计数和列表

javascript - 数组 .includes() 给出意外行为

python - Django 在速记渲染方法中添加自定义 header

python - 替代全局变量

r - 如何根据在ggplot中分配的概率对单词重新排序

angular - 类型 'null' 的参数不可分配给参数 Angular

java - 使用 java Supplier 接口(interface)创建条件对象

javascript - 使用 JavaScript 中的动态属性对数组中的所有对象项求和

java - 将 java.util.function.Function 定义为 static fi

reactjs - Eslint错误: Do not nest ternary expression