Dart - Understanding Null Safety Operators

Dart, starting from 2.12, supports a robust null safety mechanism.

After enabling null safety in Dart and Flutter, all types in the code will be non-null types by default, and their values ​​cannot be null, that is, in the code null. Unless the usage ?is declared nullable.

With null safety, the original 运行时null value reference error will become 编译时an analysis error. The advantage of this is that the null pointer exception that only occurs when the program is running is provided in the compilation base and exposed.

In order to facilitate understanding, I first define a class

class Person {
    
    
  Children children;
  work() {
    
    
    print("人在工作");
  }

  toString() {
    
    
    return "这是一个人";
  }
}

class Children {
    
    
  eat() {
    
    
    print("孩子吃饭啦");
  }
}

declare a nullable type

Adding ?an operator after the type of the declared variable means that the variable is nullable.

void main() {
    
    
  Person? p;
}

Escape operator?

If we have no way of knowing whether a nullable variable is null at runtime, but we need to call a method or property of the variable, we can use ?operators for the robustness of the code.

Person? p;
p.work();

After writing like this, the dart compiler will give an error directly because the object of the called method may be null.
We just need to add it in the call ?to avoid the no-op.

void main() {
    
    
  Person? p;
  /// 跳过运行
  p.work();
  print("程序结束");
}

Print result: The program ends.

Because p is a Null object, it p.work()will not run, just skip it.

Null Assertion Operator!

Under null safety, the following code will error.toUpperCase()compile with an error.

class HttpResponse {
    
    
  final int code;
  final String? error;

  HttpResponse.ok()
      : code = 200,
        error = null;
  HttpResponse.notFound()
      : code = 404,
        error = 'Not found';

  @override
  String toString() {
    
    
    if (code == 200) return 'OK';
    return 'ERROR $code ${
    
    error.toUpperCase()}';
  }
}

But we can artificially observe that when code is not equal to 200, error is definitely not null, but the compiler does not know the connection between code and error.

This is where the null assertion operator !comes in handy.
A suffixed exclamation mark (!) causes the expression on the left to be converted to its corresponding non-null type.

String toString() {
    
    
  if (code == 200) return 'OK';
  return 'ERROR $code ${
    
    error!.toUpperCase()}';
}

Plus !it will tell the compiler that !the variable on the left side of it must not be empty, so that it can be compiled normally.

Guess you like

Origin blog.csdn.net/adojayfan/article/details/124422421