簡體   English   中英

Flutter 空構造值

[英]Flutter Empty Constructing value

當我現在創建 object 時,如果該 object 缺少字段,則這些字段設置為 null。 如果它們是空的,是否有可能使它們不存在? 前任:

class Example {
  Example({this.username, this.email, this.fullName});
  String username;
  String email;
  String fullName;
}

Example user = Example(username: "john99", fullName: "John Doe");
// This returns a User(username: "john99", fullName: "John Doe", email: null);
// I would like to have this return the following: User(username: "john99", fullName: "John Doe");

這是最接近的:

class Example {
  String username;
  String email;

  Example._(this.username, this.email);

  factory Example({@required String username, @required String email, String fullName}) {
    if (fullName == null) return Example._(username, email);
    return _FullExample(username, email, fullName);
  }
}

class _FullExample extends Example {
  String fullName;

  _FullExample(String username, String email, this.fullName)
    : super._(username, email);
}

它看起來有點做作和過於冗長嗎? 很好,因為它應該。

Dart 不是 Javascript。 對象不是可以動態獲得或失去屬性的秘密記錄。 它是一種靜態類型語言,對類型有哪些字段和沒有哪些字段有明確的約定。 當您在 Dart class 中聲明一個字段時,該 class 的實例將具有該字段,無論它包含實例化值還是null 換句話說,Dart 沒有undefined為 static 值的概念 - 僅作為編譯時或運行時錯誤。

當您有“從類中刪除未使用的字段”之類的要求時,請退后一步,質疑您是否有正當理由提出這樣的要求,或者您是否試圖將 Dart 視為並非如此。 如果是后者,那么你最好切換到使用 Javascript 的 React Native 之類的東西,這樣的東西是慣用的,而不是讓語言向后彎曲,只是為了讓你感覺更舒服使用從未打算過的開發方法對於那種語言。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM