Nullability
Nullable & optional valuesβ
To allow nullable types ZodArt provides the .nullable() modifier for all types.
ZString(); // Allows the `String` type
ZString().nullable(); // Allows the `String?` type
In Dart, unlike JavaScript, there is no concept of undefined value. However, when parsing ZObject from Map<String, dynamic>, a missing key (!map.containsKey('key')) is the Dart equivalent of undefined.
To explicitly allow missing keys, ZodArt provides the .optional() modifier.
For all other types like ZString, ZInt, etc., there is no concept of a "missing" value. In this context, the .optional() modifier has no semantic effect and is treated as equivalent to .nullable().
ZObject Parsing (Map fields)β
.nullable()- allows the field value to benull.optional()- allows the field to be eithernullor missing from the map
| Field value | .nullable() | .optional() |
|---|---|---|
| not-null-value | β ParseSuccess (not-null-value) | β ParseSuccess (not-null-value) |
| null | β ParseSuccess (null) | β ParseSuccess (null) |
| !map.containsKey('key') | β ParseError | β ParseSuccess (null) |
Other Types Parsingβ
| Value | .nullable() | .optional() |
|---|---|---|
| not-null-value | β ParseSuccess (not-null-value) | β ParseSuccess (not-null-value) |
| null | β ParseSuccess (null) | β ParseSuccess (null) |
Handling null valuesβ
Processing and validation modifiers are skipped for null values, but sometimes you donβt just want to accept null, but also provide a default value in that case.
For this purpose, every nullable schema type supports the .onNull(fn) modifier, which is invoked whenever the current value is null.
See the full example.
import 'package:zodart/zodart.dart';
void main() {
final zString = ZString().nullable().onNull(() => 'default value');
print(zString.parse('ZodArt').value); // ZodArt
print(zString.parse(null).value); // default value
}