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(),
};
}
How to solve it?
CodePudding user response:
Make your birthday
nullable. So replace
DateTime birthday;
with
DateTime? birthday;
If you don't want it to be nullable you could instead put a non-null fallback like DateTime.now()
for example like
birthday:
json["birthday"] != null ? DateTime.parse(json["birthday"]) : DateTime.now(),
CodePudding user response:
2 work arounds
pass
non nullable
value tobirthday
:birthday: DateTime.parse(json["birthday"]) ?? DateTime.now(),
make
birthday nullable
DateTime? birthday
with this method you can keep the existing line of the code. Your error will no longer display.
CodePudding user response:
You can choose one of two codes:
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(),
};
}
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"]) : DateTime.now(),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"url": url,
"birthday": birthday?.toString(),
};
}
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.