I've those objects:
class ServerResponse {
bool successfully;
int count;
String? errorMsg;
String? errorCode;
Map<String, dynamic>? data;
ServerResponse(
{required this.successfully,
required this.count,
this.errorMsg,
this.errorCode,
this.data});
}
import 'dart:convert';
import './models.dart';
/ --------------------------------
class MyClass {
String organisationId;
String regionCode;
Culture defaultCulture;
MyClass({
required this.organisationId,
required this.regionCode,
required this.defaultCulture,
});
Map<String, dynamic> toMap() {
return {
'organisationId': organisationId,
'regionCode': regionCode,
'default culture': defaultCulture
};
}
factory MyClass.fromMap(Map<String, dynamic> map) {
return AppValidated(
organisationId: map['organisationId'],
regionCode: map['regionCode'],
defaultCulture: map['defaultCulture']);
}
String toJson() => json.encode(toMap());
factory MyClass.fromJson(String source) =>
MyClass.fromMap(json.decode(source));
}
And on my code, I've this...
ServerResponse rd = response.data;
MyClass mc = rd.data;
However, MyClass mc = rd.data is throwing me a A value of type 'Map<String, dynamic>?' can't be assigned to a variable of type 'MyClass'
How can I handle it ?
CodePudding user response:
Your class provides a fromMap
factory. Try this:
MyClass mc = MyClass.fromMap(rd.data);
CodePudding user response:
Add .fromJson constructor in MyClass
Here it is :
MyClass.fromJson(Map<String, dynamic> json) {
organisationId= json['organisationId'],
regionCode= json['regionCode'],
defaultCulture= mapjson'defaultCulture']
}
Then use it like this:
ServerResponse rd = response.data;
MyClass mc = MyClass.fromJson(rd.data);