Reputation: 627
I'm developing a chatting application using Firebase.
for some time i'm getting this error Unhandled Exception: NoSuchMethodError: The method 'toDate' was called on null.
Getting error when converting Timestamp
to DateTime
using toDate()
.
GIVES ERROR FOR SOME TIME AND THEN ERROR DISAPPEARS.
PLEASE CONSIDER THIS GIF.
HERE IS FIRESTORE DATATYPE AS TimeStamp
.
SOURCE CODE
class ChatMessageModel {
bool isSentByMe;
String msg = '';
///SERVER TIME
Timestamp time;
DateTime localTime;
String timeStamp;
String fromUid;
String toUid;
ChatMessageModel._();
ChatMessageModel.fromSnapshot(DocumentSnapshot snapshot) {
this.isSentByMe =
snapshot.data['from'] == LoginBloc.instance.firebaseUser.uid;
this.msg = snapshot.data['msg'];
this.timeStamp = snapshot.data['time'].toString();
this.time = snapshot.data['time'];
this.fromUid = snapshot.data['from'];
this.toUid = snapshot.data['to'];
this.localTime = this.time.toDate(); //ERROR
}
}
THANKS IN ADVANCE.
Upvotes: 6
Views: 4010
Reputation: 193
This code worked for me:
ds['time'] == null? Text(DateTime.now().toString())
: Text(
DateFormat("hh:mm a").format(
ds['time'].toDate(),
),
),
Upvotes: 0
Reputation: 71
It is showing error because at the calling time of this.time, this.time getting null. So toDate() function can't be able to applying on null
Try changing :
this.localTime = this.time.toDate();
To :
this.localTime = this.time == null ? DateTime.now()
: this.time.toDate();
OR You can use like this :
String stringtime = widget.time == null
? DateTime.now().toString()
: widget.time.toDate().toString();
// stringtime = widget.time.toDate().toString();
DateTime date = DateTime.parse(stringtime);
String clocktime = DateFormat('hh:mm a').format(date);
Hope it helps, worked for me :)
Upvotes: 4
Reputation: 1
try changing
this.localTime = this.time.toDate();
to
this.localTime = this.time.toDate()==null?DateTime().now():this.time.toDate();
for better readability save this.time.toDate()
in a variable.Hope it helps,worked for me
Upvotes: 0
Reputation: 7889
Your code is trying to convert time
to Date
before it is fetched, a short workaround would be initializing your time
variable with current time before server's value loads:
Timestamp time = new Timestamp( new Date(2019,3,4) );
another solution would be to use an async
method to await
the value from the server before converting it, which you can't afford given that you want to use it in instant messeging.More can be found in the official Firebase documentation and the android developer documentation.
Note that the above code will result in a Timestamp
pointing to midnight, but shouldn't be an issue since it is a brief placeholder compared to Firebase response speed.
Upvotes: 2