简体   繁体   English

Flutter 空构造值

[英]Flutter Empty Constructing value

When I create an object right now, if that object has missing fields those are set to null.当我现在创建 object 时,如果该 object 缺少字段,则这些字段设置为 null。 Is it possible to make them non-existent if they are empty?如果它们是空的,是否有可能使它们不存在? Ex:前任:

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

This is as close as it gets:这是最接近的:

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

Does it seem a bit contrived and overly verbose?它看起来有点做作和过于冗长吗? Good, because it should.很好,因为它应该。

Dart is not Javascript. Dart 不是 Javascript。 Objects aren't secretly records that can gain or lose properties dynamically.对象不是可以动态获得或失去属性的秘密记录。 It is a statically-typed language with clear contracts on what fields a type does and doesn't have.它是一种静态类型语言,对类型有哪些字段和没有哪些字段有明确的约定。 When you declare a field in a Dart class, instances of that class will have that field, whether it contains an instantiated value or null .当您在 Dart class 中声明一个字段时,该 class 的实例将具有该字段,无论它包含实例化值还是null In other words, Dart has no concept of undefined as a static value - only as a compile-time or runtime error.换句话说,Dart 没有undefined为 static 值的概念 - 仅作为编译时或运行时错误。

When you have a requirement like "remove an unused field from a class", take a step back and question whether you have a legitimate reason for having such a requirement, or if perhaps you are trying to treat Dart like something it's not.当您有“从类中删除未使用的字段”之类的要求时,请退后一步,质疑您是否有正当理由提出这样的要求,或者您是否试图将 Dart 视为并非如此。 If the latter, then you would be better off switching to something like React Native that does use Javascript where stuff like this is idiomatic instead of making the language bend over backward for you just to make you feel more comfortable using development methodologies that were never intended for that language.如果是后者,那么你最好切换到使用 Javascript 的 React Native 之类的东西,这样的东西是惯用的,而不是让语言向后弯曲,只是为了让你感觉更舒服使用从未打算过的开发方法对于那种语言。

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

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