Why does casting this string in this way work but not the other way? - flutter

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.

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.

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();

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?

Related

In Flutter, an object's fromJson method generated by freezed occured type cast error, DateTime -> String

I have used freezed library to manage my Remote DTO classes and Ui Models.
In this question case, my Object LifeDiagnosisResult DTO and Ui Model only have one difference - createdAt field.
When I put data, I used SharedPreference (because backend is not yet built) and put my List value by jsonEncode function.
When I get a response from SharedPreference (because backend is not yet built) , I used jsonDecode to get Map Object.
To achieve my final wish, List Object, I added createdAt field like this.
void _handleListResponseSuccess(List<String> response) {
List<LifeDiagnosisResultUiModel>? uiModelList = response.map((e) {
Map<String, dynamic> map = jsonDecode(e) as Map<String, dynamic>;
map['createdAt'] = DateTime.now();
return LifeDiagnosisResultUiModel.fromJson(map);
}).toList();
if (uiModelList.isNotEmpty) {
setLifeDiagnosisResultUiModel(uiModelList[uiModelList.length - 1]);
}
_rxList(uiModelList);
}
But, when I ran this code, type casting error was caused.
The error message is this.
error type 'DateTime' is not a subtype of type 'String' in type cast
And this is my Ui Model's createdAt field.
I think Map's createdAt could not find correct field in Ui Model.
But I have no idea why...
Could you tell me what is wrong?
I found the answer...
it is not a real answer of my question, but it can explain why this issue happen.
In dart, Map's DateTime cannot be converted to Object's DateTime.
I dont know a detail process, but in type casting, Map's DateTime is converted to String type.
I don't know if I get it right, but if you want to test your fromJson method you could do it like this:
Map<String,dynamic> response={'att1':1234,'att2':'oneTwoThree','createdAt':DateTime(2022,08,22)};
return LifeDiagnosisResultUiModel.fromJson(response);

type 'String' is not a subtype of type 'DateTime?'

I get the following error when adding the date information returned from the item to the "tarih", "vadeTarihi" fields whose type is DateTime
type 'String' is not a subtype of type 'DateTime?'
masterDetailTemp = masterDetailTemp.copyWith(
master: masterDetailTemp.master!.copyWith(
// the line where i got the error
tarih: item.tarih,
vadeTarihi: item.vadeTarihi,
));
Type of values returned from item:
In your SatisFaturaMaster model class. Check the type of kayitTarihi and tarih variables if they are Strings then you need to parse the DateTime to convert it to a String.
To do that;
kayitTarihi.toString(); tarih.toString();
If you want to store tarih and vadeTarihi as DateTime do the following.
masterDetailTemp = masterDetailTemp.copyWith(
master: masterDetailTemp.master!.copyWith(
// the line where i got the error
tarih: DateTime.tryParse(item.tarih),
vadeTarihi: DateTime.tryParse(item.vadeTarihi),
));
this worked:
tarih: DateTime.tryParse(item.tarih.toString()),
vadeTarihi: DateTime.tryParse(item.vadeTarihi.toString()),

how to create a Instant class variable in kotlin with my own timestamp

Till now i was using
val date = Instant.now(Clock.system(ZoneId.of("UTC")))
to generate the instant timestamp.
Now I need to substitute it with the date that I want to specify for example "2021-05-03T00:00:00.000Z". When i insert it as a string into the function, the idea gives me the error "Type mismatch. Required: Instant! Found: String". I can't change the function as I have no such access to it. So i need to somehow turn this date into "Instant!" class.
this is how the function that i can't change looks like
public TimeTZ(Instant timestamp, Boolean isLocal) {
this.timestamp = timestamp;
this.isLocal = isLocal;
}
val date = Instant.parse("2021-05-03T00:00:00.000Z")
Converting a string to an Instant (or other typed value) is called parsing. So use the parse method of Instant.

C++Builder - cannot cast from 'AnsiString' to 'TObject'

I have a problem with converting a string variable to TObject.
I have a query that returns two columns to me. In the first column I have varchar values that I translate into strings, and in the second column I have int values.
I want to fill a ComboBox in this way with these values:
cbx1-> AddItem (DataSet1->DataSet->Fields->Field[0]->AsString, (TObject *) (int) DataSet1->DataSet->Fields->Field[1];
As I refer to the second value which is int type, I receive some bushes, e.g., xD, etc.
By trying to convert this value to string, eg:
String temp = IntToStr (DataSet1->DataSet->Fields->Field[1]);
cbx1-> AddItem (DataSet1->DataSet->Fields->Field[0]->AsString, (TObject *) temp;
I receive an error message:
cannot cast from 'AnsiString' to 'TObject'
I do not know what further I can do to convert this value.
You cannot cast an AnsiString value to a TObject* pointer. You can only cast an integer value, or a pointer value, to a TObject* pointer. AnsiString is neither of those.
You are not retrieving the int value from the 2nd field correctly anyway. Field[1] is a pointer to an actual TField object in the Fields collection. That pointer is what you are trying to store in your ComboBox, NOT the int value that the TField represents.
You need to call Fields[1]->AsInteger to get the int value of the 2nd field, similar to how you use Fields[0]->AsString to get the string value of the 1st field:
cbx1->AddItem(
DataSet1->DataSet->Fields->Field[0]->AsString,
(TObject*) DataSet1->DataSet->Fields->Field[1]->AsInteger
// in C++, using reinterpret_cast is preferred over C-style casting:
// reinterpret_cast<TObject*>(DataSet1->DataSet->Fields->Field[1]->AsInteger)
);
This is no different than the code in your previous question:
cbx1->AddItem("one",(TObject*)1);
You are now just placing the literals "one" and 1 with runtime variables of equivalent types.

Struts 2 - Date instance become String

When I submit the form, input error is occur. JourneyDate is instance of 'Date'. But ,here it become String which is not accepted by the setter and getter.
<s:hidden name="JourneyDate" value="%{JourneyDate}"></s:hidden>
I want JourneyPlan as Date Type, but it become String.
Try intercepting the value before passing it to the getter/setter. For example send JourneyDateString from your form, create a Date from the String, and then pass that to your getter/setter. Something like:
public void setJourneyDateString(String journeyDateString)
{
//journeyDateString could be "2013-03-28" for example
Date journeyDate = new SimpleDateFormat("yyyy-MM-dd").parse(journeyDateString);
setJourneyDate(journeyDate);
}
The object that you've set in the value attribute will keep it's type as Date. Then you need to define corresponding setter in the action to set the value of the Date. It will convert to string if you place the value in the body of the tag.