简体   繁体   English

如果变量不是 Dart 中的一行代码中的 null,如何有条件地执行代码?

[英]How to conditionally execute code if a variable is NOT null in one line of code in Dart?

In Dart, how do we do an operation only if a variable is NOT null... and accomplish that in one line?在 Dart 中,我们如何仅在变量不是 null 时才执行操作...并在一行中完成?

Example:例子:

void main() {
  
  int? i; // pretend we don't know if it's null or not
  
  // the laborious way:
  if (i == null) {
    print("the variable is null");
  }
  
  // the one-line way:
  i ?? print("the variable is null");
  
  // the laborious way:
  if (i != null) {
    print("the variable is not null");
  }
  
  // the one-line way:
   
  // i <what opertaor goes here?> print("the variable is null")
  
}

Actually, if you remove body params'{}' it is single line.实际上,如果您删除正文参数'{}',它就是单行。

 if (i == null) print("if (i == null), the variable is not null");

Also you can do something with ternary.你也可以用三元做一些事情。 but seems having extra null.但似乎有额外的 null。

i == null ? print("i==null, the variable is not null") : null;

You can use this extension, you can return bool based on your need.您可以使用此扩展,您可以根据需要返回布尔值。

extension NullChecker<T> on T? {
  get isNull => print("This variable is ${this != null ? "not" : ""} null");
}

And use,并使用,

void main() {
  int? i = 4, j;
  i.isNull; //This variable is not null
  j.isNull; //This variable is  null
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM