I tried to fetch users’Users data from Firebase Firestore. For that I created a model class.And also in those data has a birthday parameter I tried to define that in model but show this error "The argument type ‘DateTime?’ can’t be assigned to the parameter type ‘DateTime’"
My code:
import 'dart:convert';
Users UsersFromJson(String str) => Users.fromJson(json.decode(str));
String UsersToJson(Users data) => json.encode(data.toJson());
class Users {
Users({
required this.id,
required this.url,
required this.name,
required this.birthday,
});
String id;
String name;
String url;
DateTime birthday;
factory Users.fromJson(Map<String, dynamic> json) => Users(
id: json["id"] ?? "",
name: json["name"] ?? "",
url: json["url"] ?? "",
birthday: json["birthday"] != null ? DateTime.parse(json["birthday"]) : null,
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"url": url,
"birthday": birthday?.toString(),
};
}
3
Answers
Make your
birthday
nullable. So replacewith
If you don’t want it to be nullable you could instead put a non-null fallback like
DateTime.now()
for example like2 work arounds
pass
non nullable
value tobirthday
:make
birthday nullable
with this method you can keep the existing line of the code. Your error will no longer display.
You can choose one of two codes:
However, I recommend that you use the first code more, because if the
birthday
field is null, you can show the user that there is no data.If you use the second code, I don’t think there is any way to check if the
birthday
field is empty.