Skip to content

Instantly share code, notes, and snippets.

@aaronkelton
Last active May 29, 2024 19:49
Show Gist options
  • Save aaronkelton/75e8f81e6617bce6802f387040818b71 to your computer and use it in GitHub Desktop.
Save aaronkelton/75e8f81e6617bce6802f387040818b71 to your computer and use it in GitHub Desktop.
How does null pass into a factory's method signature with an optional param and default value?
void main() {
Map<String, dynamic> json = {'type': null};
try {
ElementType too = ElementType.fromString(null); // passes null through (explicitly)
ElementType foo = ElementType.fromString(json['type']); // passes null through (explicitly via map)
ElementType bar = ElementType.fromString(json['key_missing']); // passes null through (implicitly via map)
ElementType baz = ElementType.fromString(); // does NOT pass null; factory uses 'default string'
HashyType bro = HashyType.fromString(stringValue: null); // passes null through (explicitly)
HashyType was = HashyType.fromString(stringValue: json['type']); // passes null through (explicitly via map)
HashyType sup = HashyType.fromString(stringValue: json['key_missing']); // passes null through (implicitly via map)
HashyType dud = HashyType.fromString(); // does NOT pass null; factory uses 'default string'
} catch (e) {
print("Error: $e");
}
}
enum ElementType {
audio;
factory ElementType.fromString([String? stringValue = 'default string']) {
print("String value passed through: $stringValue");
return audio;
}
}
enum HashyType {
bar;
factory HashyType.fromString({String? stringValue = 'default string'}) {
print("String value passed through: $stringValue");
return bar;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment