簡體   English   中英

如果變量不是 Dart 中的一行代碼中的 null,如何有條件地執行代碼?

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

在 Dart 中,我們如何僅在變量不是 null 時才執行操作...並在一行中完成?

例子:

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")
  
}

實際上,如果您刪除正文參數'{}',它就是單行。

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

你也可以用三元做一些事情。 但似乎有額外的 null。

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

您可以使用此擴展,您可以根據需要返回布爾值。

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

並使用,

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