Reputation: 18379
I have a DateTime field in my model, which has null value. Am using json_serializable library to handle serialization/deserialization. Its failing while serializing a dattime field which has null value.
@JsonSerializable(nullable: false, includeIfNull: false)
class Customer{
DateTime eventTime; //Field with null value
//others
factory Customer.fromJson(Map<String, dynamic> json) => _$CustomerFromJson(json);
Map<String, dynamic> toJson() => _$CustomerToJson(this);
}
Exception:
9-10-27 11:28:47.724 31431-31463/E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'toIso8601String' was called on null.
Receiver: null
Tried calling: toIso8601String()
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _$CustomerToJson (/models/customer.g.dart:74:41)
Upvotes: 0
Views: 909
Reputation: 3263
If values can be null you need to use nullable property
@JsonKey(nullable: false)
DateTime eventTime;
nullable property
When true, null fields are handled gracefully when encoding to JSON and when decoding null and nonexistent values from JSON.
Setting to false eliminates null verification in the generated code for the annotated field, which reduces the code size. Errors may be thrown at runtime if null values are encountered, but the original class should also implement null runtime validation if it's critical.
The default value, null, indicates that the behavior should be acquired from the JsonSerializable.nullable annotation on the enclosing class.
Upvotes: 2