Reputation: 39
When I create an object right now, if that object has missing fields those are set to 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");
Upvotes: 0
Views: 6408
Reputation: 24746
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. 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
. In other words, Dart has no concept of undefined
as a static value - only as a compile-time or runtime error.
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. 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.
Upvotes: 2