不能无条件地调用运算符“*”,因为接收者可以是 'null'。尝试向目标添加空检查('!')

The operator '*' can't be unconditionally invoked because the receiver can be 'null'. Try adding a null check to the target ('!')

我在 UI 中使用此代码来提高响应能力。所以这段代码基本上做的是计算屏幕的大小,我使用下面的函数根据 Figma 或 Adob​​e XD 中提供给我的设计来放置准确的字体大小。使用这种方法,我能够创建像素完美 UI.

升级到 Flutter 2.0.3 后,我收到空安全错误。我能够解决其中的大部分问题,但我无法解决此错误。 请指教

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

因为SizeConfig.defaultSize可以为空,你需要确保它的值不应该为空。

您可以添加一些断言来通知调用者 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);
}

问题:

您收到此错误是因为您正在调用 * 的对象可以是 null.

示例:

int? count = 1;

void main() {
  print(count * 2); // error: The operator '*' can't be unconditionally invoked ...
}

解法:

  • 使用局部变量:

    int? count = 1;
    
    void main() {
      var i = count;
      if (i != null) {
        print(i * 2); // Prints 2
      }
    }
    
  • 使用 bang 运算符 (!)

    int? count = 1;
    
    void main() {
      print(count! * 2); // Prints 2
    }
    

您有三个选择:

  • 使用 bang 运算符:
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);
}
  • 使用 if - else 语句:
int? count = 1;

void main() {
  if(count != null) {
    print(count! * 2);
  } else {
    print('count is null');
  }
}