I have the starts and ends fields in my model as Timestamp, but I am getting this error. I don't get it when I define start and end as var in my Model.
Unhandled Exception: type 'Null' is not a subtype of type 'Timestamp'
Model:
import 'package:cloud_firestore/cloud_firestore.dart';
class Event {
String eid;
String title;
String location;
Timestamp start;
Timestamp end;
String instructor;
String image;
String description;
Event({
required this.eid,
required this.title,
required this.location,
required this.start,
required this.end,
required this.instructor,
required this.image,
required this.description
});
factory Event.fromMap(Map<String, dynamic>? map) {
return Event(
eid: map?['eid'] ?? 'undefined',
title: map?['title'] ?? 'undefined',
location: map?['location'] ?? 'undefined',
start: map?['starts'],
end: map?['ends'],
instructor: map?['instructor'] ?? 'undefined',
image: map?['image'] ?? 'undefined',
description: map?['description'] ?? 'undefined'
);
}
You are getting null
value for start
and end
, you need to define a default value for them like other variable:
factory Event.fromMap(Map<String, dynamic>? map) {
return Event(
eid: map?['eid'] ?? 'undefined',
title: map?['title'] ?? 'undefined',
location: map?['location'] ?? 'undefined',
start: map?['starts'] ?? Timestamp(0, 0),//<--- add this
end: map?['ends'] ?? Timestamp(0, 0),//<--- add this
instructor: map?['instructor'] ?? 'undefined',
image: map?['image'] ?? 'undefined',
description: map?['description'] ?? 'undefined'
);
}
start: map?['starts'],
end: map?['ends'],
What you are doing here is setting the start/end arguments to the map from firestore, but if the document doesn't have that field, you have no fallback and it returns null
.
Do one of either:
start: map?['starts'] ?? Timestamp.now(),
end: map?['ends'] ?? Timestamp.now(),
class Event {
// ...
Timestamp? start;
Timestamp? end;
This is because you are not giving a default value (the same way you are doing for all other variables):
?? 'undefined'
One possible solution is to allow for null
values... just add ?
for both variables definitions, like this:
class Event {
String eid;
String title;
String location;
Timestamp? start; // *** change 1
Timestamp? end; // *** change 2
String instructor;
String image;
String description;
Let me know if this does not work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.