我正在使用 JSON Annotation Flutter 包,'null check operator used on a null value'當我嘗試在我的用戶模型中設定時間戳時出現以下錯誤,我不明白時間戳可以為空,因為我并不總是設定它。
這是我的用戶模型:
@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);
}
我的 dateTimeAsIs 代碼:
Timestamp? dateTimeAsIs(DateTime? dateTime) {
return Timestamp.fromDate(dateTime!);
}
DateTime dateTimeFromTimestamp(Timestamp timestamp) {
return DateTime.parse(timestamp.toDate().toString());
}
呼叫一切:
// 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);
火庫:
// 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(),
);
}
}
uj5u.com熱心網友回復:
Timestamp? dateTimeAsIs(DateTime? dateTime) {
return dateTime == null ? null : Timestamp.fromDate(dateTime);
}
您允許該方法傳入 null,但顯式回傳它。你必須傳遞一個 DateTime.now() 或任何你需要傳遞給 dateTimeAsIs 的時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/434600.html
