繁体   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