Home > other >  Why does casting this string in this way work but not the other way?
Why does casting this string in this way work but not the other way?

Time:10-10

I am reading data from Firestore. I was getting an error that said type 'Timestamp' is not a subtype of type 'String' in type cast, so I changed the createDate line below to use .toString() instead of doing as String. This solved the problem, but why did this work?

Notification.fromJson(Map<dynamic, dynamic>? json): //Transform JSON into Notification
        createDate = (json?['createDate']).toString(), //This works
        modifiedDate = json?['modifiedDate'] as String; //This gives the error: 'type 'Timestamp' is not a subtype of type 'String' in type cast'

The format of both of these fields is October 5, 2022 at 10:49 PM UTC-5.

CodePudding user response:

json?['createDate'] is a Timestamp type object that just contains numbers describing a point in time. As you can see from the API documentation, it has a method called toString that knows how to convert that to formatted date string. Since a Timestamp it is not a subclass of String, Dart does not allow it to be cast to one. Perhaps you want to cast it to Timestamp instead, since that's what it is?

CodePudding user response:

Like it is said in error message, you are getting this error, because the value's type, which is coming from json is Timestamp, not String. It is better to make createDate and modifiedDate fields in Timestamp type instead of String, because it provides it's own methods, that make your work easier. Converting to String (and probably, you are parsing this String in somewhere) is redundant.

CodePudding user response:

In Flutter every object class have toString() method, which is return a value with String type

(json?['createDate']).toString();

So if you write that code above, it will return a value with String type and then assign that value to createDate variable. It means you not assign json?['createDate'].

modifiedDate = json?['modifiedDate'] as String;

That line above will error because you assign that json to modifiedDate which is have different type. Cast (as) only work if the object/variable have same hierarchy, like

Child child = Child();
Parent parent = child as Parent();
  • Related