Issue
I'm using the JSON Annotation Flutter package and I'm getting the following error 'null check operator used on a null value'
when I try to set a timestamp in my user model what I don't understand the timestamp can be null as I don't always set it.
Here is my user model:
@JsonSerializable(explicitToJson: true)
class UserModel {
String userId;
String email;
String firstName;
String lastName;
@JsonKey(fromJson: dateTimeFromTimestamp, toJson: dateTimeAsIs)
DateTime? recentTraining;
@DocumentSerializerNullable()
DocumentReference? recentTrainingRef;
int? dogsCount;
int? totalTrainingSessions;
int? totalTrainingTime; // in min
int? totalTrainingDays;
@JsonKey(fromJson: dateTimeFromTimestamp, toJson: dateTimeAsIs)
DateTime? createdAt;
UserModel({
required this.userId,
required this.email,
required this.firstName,
required this.lastName,
this.recentTraining,
this.recentTrainingRef,
this.dogsCount,
this.totalTrainingSessions,
this.totalTrainingTime,
this.totalTrainingDays,
this.createdAt,
});
factory UserModel.fromJson(Map<String, dynamic> json) =>
_$UserModelFromJson(json);
Map<String, dynamic> toJson() => _$UserModelToJson(this);
}
My dateTimeAsIs code:
Timestamp? dateTimeAsIs(DateTime? dateTime) {
return Timestamp.fromDate(dateTime!);
}
DateTime dateTimeFromTimestamp(Timestamp timestamp) {
return DateTime.parse(timestamp.toDate().toString());
}
Calling everything:
// User Model
final UserModel userModelObject = UserModel(
email: email,
firstName: firstName,
lastName: lastName,
userId: authResult.user!.uid,
);
// Calls the dog Firebase service
await UsersFirestoreService().createUser(userModelObject);
Firestore:
// Creates the user doc and sets the data
Future<dynamic> createUser(UserModel user) async {
try {
return await usersCollection
.doc(user.userId)
.set(user.toJson()); // user.toJson() //{'firstName': user.firstName}
} on FirebaseException catch (error) {
throw CustomException(
message: 'Future Error createUser',
subMessage: error.message.toString(),
);
}
}
Solution
Timestamp? dateTimeAsIs(DateTime? dateTime) {
return dateTime == null ? null : Timestamp.fromDate(dateTime);
}
You allow that method to pass in null, but explicitly return off it. You have to pass a DateTime.now() or whatever time you need to pass into dateTimeAsIs.
Answered By - jbryanh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.