0

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.

enter image description here

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?

Jun
  • 451
  • 4
  • 16
  • If I understand correctly, you are reading data from the "backend response". Why do you want to change the date afterwards? This information should come from the backend, shouldn't it? – MCB Aug 22 '22 at 08:49
  • Yeah you r right! It is not necessary. If a backend was deployed, this question is useless - because the backend will send a response with createdAt, updatedAt etc... But, i dont deploy backend yet, So I just wanted to test it by SharedPrefernce, and found this error. Logically, you r right but, I'd like to know why Map -> Object casting occurs this error, just.... – Jun Aug 22 '22 at 08:56

2 Answers2

1

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.

Jun
  • 451
  • 4
  • 16
0

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);
MCB
  • 503
  • 1
  • 8
  • 21
  • Thank u for ur answer! But I found that datetime does not support clean?? casting... So we have to use a jsonconverter like this...https://stackoverflow.com/questions/60793441/how-do-i-resolve-type-timestamp-is-not-a-subtype-of-type-string-in-type-cast – Jun Aug 22 '22 at 11:38