Related
I am calling an XML format API and converting it to Json to use it within a Flutter mobile app
I am using xml2Json and it is converting fine
As seen below I call print(jsonMap); and it displays the correct Json data in GData format
I then take my Json parse model, built with Quicktype.io off of the Json model and call locations = Locations.fromJson(jsonMap); as seen below to allow to to draw the required data out. I am currently then just calling print(locations); to check whether its working and the data is returning before implementing the parsed data into the app fully.
I have tried shuffling round everything, I've adapted the Model several times and tried all kinds of methods to parse the data.
I am calling other APIs with the exact same method successfully and the code method is identical in this one. The only difference is the xml2Json convert, which is converting fine (JsonMap printing converted XML correctly), so I'm struggling the see what should be different.
Thanks for reading
The call
Future<Locations> fetchLiveLocations() async {
var client = http.Client();
var locations;
Xml2Json xml2Json = new Xml2Json();
try{
var response = await client.get('API_CALL');
if (response.statusCode == 200) {
xml2Json.parse(response.body);
var jsonString = xml2Json.toGData();
var jsonMap = json.decode(jsonString);
print(jsonMap);
locations = Locations.fromJson(jsonMap);
print(locations);
}
} catch(Exception) {
return locations;
}
return locations;
}
Model
import 'dart:convert';
Locations locationsFromJson(String str) => Locations.fromJson(json.decode(str));
String locationsToJson(Locations data) => json.encode(data.toJson());
class Locations {
Locations({
this.vehicleActivity,
});
List<VehicleActivity> vehicleActivity;
factory Locations.fromJson(Map<String, dynamic> json) => Locations(
vehicleActivity: List<VehicleActivity>.from(json["VehicleActivity"].map((x) => VehicleActivity.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"VehicleActivity": List<dynamic>.from(vehicleActivity.map((x) => x.toJson())),
};
}
class VehicleActivity {
VehicleActivity({
this.recordedAtTime,
this.itemIdentifier,
this.validUntilTime,
this.monitoredVehicleJourney,
this.extensions,
});
DateTime recordedAtTime;
String itemIdentifier;
DateTime validUntilTime;
MonitoredVehicleJourney monitoredVehicleJourney;
Extensions extensions;
factory VehicleActivity.fromJson(Map<String, dynamic> json) => VehicleActivity(
recordedAtTime: DateTime.parse(json["RecordedAtTime"]),
itemIdentifier: json["ItemIdentifier"],
validUntilTime: DateTime.parse(json["ValidUntilTime"]),
monitoredVehicleJourney: MonitoredVehicleJourney.fromJson(json["MonitoredVehicleJourney"]),
extensions: Extensions.fromJson(json["Extensions"]),
);
Map<String, dynamic> toJson() => {
"RecordedAtTime": recordedAtTime.toIso8601String(),
"ItemIdentifier": itemIdentifier,
"ValidUntilTime": validUntilTime.toIso8601String(),
"MonitoredVehicleJourney": monitoredVehicleJourney.toJson(),
"Extensions": extensions.toJson(),
};
}
class Extensions {
Extensions({
this.vehicleJourney,
});
VehicleJourney vehicleJourney;
factory Extensions.fromJson(Map<String, dynamic> json) => Extensions(
vehicleJourney: VehicleJourney.fromJson(json["VehicleJourney"]),
);
Map<String, dynamic> toJson() => {
"VehicleJourney": vehicleJourney.toJson(),
};
}
class VehicleJourney {
VehicleJourney({
this.operational,
this.vehicleUniqueId,
this.driverRef,
});
Operational operational;
int vehicleUniqueId;
int driverRef;
factory VehicleJourney.fromJson(Map<String, dynamic> json) => VehicleJourney(
operational: Operational.fromJson(json["Operational"]),
vehicleUniqueId: json["VehicleUniqueId"],
driverRef: json["DriverRef"],
);
Map<String, dynamic> toJson() => {
"Operational": operational.toJson(),
"VehicleUniqueId": vehicleUniqueId,
"DriverRef": driverRef,
};
}
class Operational {
Operational({
this.ticketMachine,
});
TicketMachine ticketMachine;
factory Operational.fromJson(Map<String, dynamic> json) => Operational(
ticketMachine: TicketMachine.fromJson(json["TicketMachine"]),
);
Map<String, dynamic> toJson() => {
"TicketMachine": ticketMachine.toJson(),
};
}
class TicketMachine {
TicketMachine({
this.ticketMachineServiceCode,
this.journeyCode,
});
dynamic ticketMachineServiceCode;
int journeyCode;
factory TicketMachine.fromJson(Map<String, dynamic> json) => TicketMachine(
ticketMachineServiceCode: json["TicketMachineServiceCode"],
journeyCode: json["JourneyCode"],
);
Map<String, dynamic> toJson() => {
"TicketMachineServiceCode": ticketMachineServiceCode,
"JourneyCode": journeyCode,
};
}
class MonitoredVehicleJourney {
MonitoredVehicleJourney({
this.lineRef,
this.directionRef,
this.publishedLineName,
this.operatorRef,
this.destinationRef,
this.vehicleLocation,
this.blockRef,
this.vehicleJourneyRef,
this.vehicleRef,
});
int lineRef;
String directionRef;
int publishedLineName;
String operatorRef;
int destinationRef;
VehicleLocation vehicleLocation;
int blockRef;
String vehicleJourneyRef;
int vehicleRef;
factory MonitoredVehicleJourney.fromJson(Map<String, dynamic> json) => MonitoredVehicleJourney(
lineRef: json["LineRef"],
directionRef: json["DirectionRef"],
publishedLineName: json["PublishedLineName"],
operatorRef: json["OperatorRef"],
destinationRef: json["DestinationRef"],
vehicleLocation: VehicleLocation.fromJson(json["VehicleLocation"]),
blockRef: json["BlockRef"],
vehicleJourneyRef: json["VehicleJourneyRef"],
vehicleRef: json["VehicleRef"],
);
Map<String, dynamic> toJson() => {
"LineRef": lineRef,
"DirectionRef": directionRef,
"PublishedLineName": publishedLineName,
"OperatorRef": operatorRef,
"DestinationRef": destinationRef,
"VehicleLocation": vehicleLocation.toJson(),
"BlockRef": blockRef,
"VehicleJourneyRef": vehicleJourneyRef,
"VehicleRef": vehicleRef,
};
}
class VehicleLocation {
VehicleLocation({
this.longitude,
this.latitude,
});
double longitude;
double latitude;
factory VehicleLocation.fromJson(Map<String, dynamic> json) => VehicleLocation(
longitude: json["Longitude"].toDouble(),
latitude: json["Latitude"].toDouble(),
);
Map<String, dynamic> toJson() => {
"Longitude": longitude,
"Latitude": latitude,
};
}
Response when I request specific data from the model
NoSuchMethodError (NoSuchMethodError: The getter 'vehicleActivity' was called on null.
Receiver: null
The JSON request has been split into two json object in the DataList JSONArray , because data is too large, how do i combine these two objects before i can decompress and get the values . Iam new to dart and flutter , any help would be appreciated. Thank you.
"DataList": [
{
"Data": "compressedata"
},
{
"Data": "compressedData"
}
],
here is what i have tried
class ResponseList {
List<DataList> dataList;
ResponseList({ this.DataList});
ResponseList.fromJson(Map<String, dynamic> json) {
if (json['DataList'] != null) {
DataList = new List<DataList>();
json['DataList'].forEach((v) {
dataList.add(new DataList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = new Map<String, dynamic>();
if (this.DataList != null) {
map['DataList'] = this.dataList.map((v) => v.toJson()).toList();
}
return map;
}
}
class DataList {
String data;
DataList({this.data});
DataList.fromJson(Map<String, dynamic> json) {
data = json['Data'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = new Map<String, dynamic>();
map['Data'] = this.data;
return map;
}
}
Using the Datalist array you can do the following:
var dataList = [
{"Data": "compressedata"},
{"Data": "compressedData"}
];
var compressedData = dataList
.map((item) => item["Data"])
.reduce((value, element) => value + element);
print(compressedData); // compressedatacompressedData
I am trying to read a JSON code which is compatible with a Swift program into a flutter app. The structure is like this:
{
"tagDict" : {
"abc" : {
"helpHdr" : "short text1",
"helpText" : "long text1"
},
"def" : {
"helpHdr" : "short text2",
"helpText" : "long text2"
}
}
}
This creates in Swift a dictionary and shall create a map in Dart of the type {key : {helpHdr, helpText}}. A variable based on this should enable label = myVariable[tag].helpHdr, or staying with the example label = myVariable["abc"].helpHdr should assign "short text1" to label
To parse nested arrays I am using this, however, no clue how to transfer this to such a nested map.
class MyClass {
List<MySubClass> myArray;
MyClass({
this.myArray,
});
factory MyClass.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson['myArray'] as List;
List<MySubClass> listObject = list.map((i) => MySubClass.fromJson(i)).toList();
return new MyClass(
myArray: listObject,
);
}
}
class MySubClass {
int id;
String text1;
String text2;
MySubClass({
this.id,
this.text1,
this.text2,
});
factory MySubClass.fromJson(Map<String, dynamic> parsedJson){
return new MySubClass(
id: parsedJson['id'],
text1: parsedJson['text1'],
text2: parsedJson['text2'],
);
}
}
If I'm correct you want to parse your json into Data class object. If that's right then you can try this
void main() {
List<MyClass> myClassList = new List<MyClass>();
Map map = {
"tagDict": {
"abc": {"helpHdr": "short text1", "helpText": "long text1"},
"def": {"helpHdr": "short text2", "helpText": "long text2"}
}
};
map['tagDict'].forEach((key, value) {
value['id'] = key;
myClassList.add(MyClass.fromJson(value));
});
myClassList.forEach((myClass) {
print(myClass.id);
print(myClass.helpHdr);
print(myClass.helpText);
print("--------------------\n");
});
}
class MyClass {
String id;
String helpHdr;
String helpText;
MyClass({this.id, this.helpHdr, this.helpText});
MyClass.fromJson(Map<String, dynamic> json) {
id = json['id'];
helpHdr = json['helpHdr'];
helpText = json['helpText'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['helpHdr'] = this.helpHdr;
data['helpText'] = this.helpText;
return data;
}
}
This is the Output:
abc
short text1
long text1
--------------------
def
short text2
long text2
--------------------
class TagRes {
TagDict tagDict;
TagRes({this.tagDict});
TagRes.fromJson(Map<String, dynamic> json) {
tagDict =
json['tagDict'] != null ? new TagDict.fromJson(json['tagDict']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.tagDict != null) {
data['tagDict'] = this.tagDict.toJson();
}
return data;
}
}
class TagDict {
Abc abc;
Abc def;
TagDict({this.abc, this.def});
TagDict.fromJson(Map<String, dynamic> json) {
abc = json['abc'] != null ? new Abc.fromJson(json['abc']) : null;
def = json['def'] != null ? new Abc.fromJson(json['def']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.abc != null) {
data['abc'] = this.abc.toJson();
}
if (this.def != null) {
data['def'] = this.def.toJson();
}
return data;
}
}
class Abc {
String helpHdr;
String helpText;
Abc({this.helpHdr, this.helpText});
Abc.fromJson(Map<String, dynamic> json) {
helpHdr = json['helpHdr'];
helpText = json['helpText'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['helpHdr'] = this.helpHdr;
data['helpText'] = this.helpText;
return data;
}
}
Based on Tipu's answer, I came up with the following code which creates the intended dictionary (or map in Dart - why couldn't they stick to standard terminology like arrays etc?!)
class TaskTags {
var tagDict = Map<String, TaskTag>();
TaskTags({
this.tagDict,
});
factory TaskTags.fromJson(Map<String, dynamic> json){
var innerMap = json['tagDict'];
var tagMap = Map<String, TaskTag>();
innerMap.forEach((key, value) {
tagMap.addAll({key: TaskTag.fromJson(value)});
});
return new TaskTags(
tagDict: tagMap,
);
}
}
class TaskTag {
String helpHdr;
String helpText;
TaskTag({
this.helpHdr,
this.helpText,
});
factory TaskTag.fromJson(Map<String, dynamic> json){
return new TaskTag(
helpHdr: json['helpHdr'],
helpText: json['helpText'],
);
}
}
This creates the following map
{"abc“ : {helpHdr: "short text1", helpText: "long text1"}, "def“ : {helpHdr: "short text2", helpText: "long text2"}}
i started having an issue recently. I need to parse my json response to a list to my model object class but i keep getting this error:
type 'String' is not a subtype of type 'int' of 'index'
tried several solutions online but it didn't work for me. I was thing my variable declarations in my model class was the issue so i changed them to dynamic but didnt still work for me.
Heading
Model
class MenteeIndex {
dynamic id;
dynamic mentor_id;
dynamic mentee_id;
dynamic status;
dynamic session_count;
dynamic current_job;
dynamic email;
dynamic phone_call;
dynamic video_call;
dynamic face_to_face;
dynamic created_at;
dynamic updated_at;
MenteeIndex(this.id, this.mentor_id, this.mentee_id, this.status, this.session_count, this.current_job,
this.email, this.phone_call, this.video_call, this.face_to_face, this.created_at, this.updated_at);
Map<String, dynamic> toJson() => {
'id': id,
'mentor_id': mentor_id,
'mentee_id': mentee_id,
'status': status,
'session_count': session_count,
'current_job': current_job,
'email':email,
'phone_call': phone_call,
'video_call': video_call,
'face_to_face': face_to_face,
'created_at': created_at,
'updated_at': updated_at,
};
MenteeIndex.fromJson(Map<String, dynamic> json):
id = json['id'],
mentor_id = json['mentor_id'],
mentee_id = json['mentee_id'],
status = json['status'],
session_count = json['session_count'],
current_job = json['current_job'],
email = json['email'],
phone_call = json['phone_call'],
video_call = json['video_call'],
face_to_face = json['face_to_face'],
created_at = json['created_at'],
updated_at = json['updated_at'];
}
Main
Future fetchIndex() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var uri = NetworkUtils.host + AuthUtils.endPointIndex;
try {
final response = await http.get(
uri,
headers: {'Accept': 'application/json', 'Content-Type': 'application/json','Authorization': 'Bearer ' + sharedPreferences.get("token"), },
);
var encodeFirst = json.encode(response.body);
final responseJson = json.decode(encodeFirst);
//here is where the error is
for (var u in responseJson["data"]) {
MenteeIndex user = MenteeIndex(
u["id"],
u["mentor_id"],
u["mentee_id"],
u["status"],
u["session_count"],
u["current_job"],
u["email"],
u["phone_call"],
u["video_call"],
u["face_to_face"],
u["created_at"],
u["updated_at"]);
menteeIndexes.add(user);
setState((){
mentorIdList = menteeIndexes.map((MenteeIndex) => MenteeIndex.mentor_id);
indexIds = menteeIndexes.map((MenteeIndex) => MenteeIndex.id);
status = menteeIndexes.map((MenteeIndex) => MenteeIndex.status);
});
}
return responseJson;
} catch (exception) {
print(exception);
}
}
Response/Error
{"current_page":1,"data":[{"id":13,"mentor_id":"5","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-20 20:37:50","updated_at":"2020-02-20 20:37:50"},{"id":14,"mentor_id":"8","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-21 22:39:31","updated_at":"2020-02-21 22:39:31"},{"id":15,"mentor_id":"10","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:15:23","updated_at":"2020-02-23 05:15:23"},{"id":16,"mentor_id":"191","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:17:34","updated_at":"2020-02-23 05:17:34"},{"id":17,"mentor_id":"141","mentee_id":"184","status":"1",
I/flutter (20995): type 'String' is not a subtype of type 'int' of 'index'
Decode the response body to Map
final responseJson = json.decode(response.body);
Convert the Map list to MenteeIndex list
final menteeIndexes = responseJson["data"].map(
(json) => MenteeIndex.fromJson(json)
).toList();
Check out this model class
// To parse this JSON data, do
//
// final yourModel = yourModelFromJson(jsonString);
import 'dart:convert';
YourModel yourModelFromJson(String str) => YourModel.fromJson(json.decode(str));
String yourModelToJson(YourModel data) => json.encode(data.toJson());
class YourModel {
int currentPage;
List<Datum> data;
YourModel({
this.currentPage,
this.data,
});
factory YourModel.fromJson(Map<String, dynamic> json) => YourModel(
currentPage: json["current_page"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"current_page": currentPage,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
int id;
String mentorId;
String menteeId;
dynamic status;
int sessionCount;
dynamic currentJob;
dynamic email;
dynamic phoneCall;
dynamic videoCall;
dynamic faceToFace;
DateTime createdAt;
DateTime updatedAt;
Datum({
this.id,
this.mentorId,
this.menteeId,
this.status,
this.sessionCount,
this.currentJob,
this.email,
this.phoneCall,
this.videoCall,
this.faceToFace,
this.createdAt,
this.updatedAt,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
mentorId: json["mentor_id"],
menteeId: json["mentee_id"],
status: json["status"],
sessionCount: json["session_count"],
currentJob: json["current_job"],
email: json["email"],
phoneCall: json["phone_call"],
videoCall: json["video_call"],
faceToFace: json["face_to_face"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"mentor_id": mentorId,
"mentee_id": menteeId,
"status": status,
"session_count": sessionCount,
"current_job": currentJob,
"email": email,
"phone_call": phoneCall,
"video_call": videoCall,
"face_to_face": faceToFace,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
Just insert you response.body to this method :
final yourModel = yourModelFromJson(response.body);
you can just get the list of data using below call :
List<Datum> dataList = List();
dataList = yourModel.data;
here you get the list of data
You will get your Single object from it and then depending on that you can do what ever you want.
I am trying to work with firebase database from flutter. I have made a model class which I am converting to json and from json via plugin json_serializable. Where model class works perfectly fine with hard coded json data but when I am trying to save the encoded data to firebase database it's getting saved as a string instead of key value pair in firebase database.Below is my code to convert it and save it
List<Action> actions = [];
actions.add(new Action('This is label', 'mranuran.com'));
EgluCard egluCard = new EgluCard(true, true, "HI", "World", "Awesome",CardType.TYPE_1 , ["images"], 123, 125, "#FFFFFF", PlatformType.IOS, actions);
//print(json.encode(egluCard));
// var jsonString = '{"isInternal":true,"isPublished":true,"title":"HI","body":"World","caption":"Awesome","cardType":"TYPE_1","images":["images"],"expiry":123,"showAt":125,"bgColor":"#FFFFFF","platformType":"IOS","actions":[{"label":"This is label","url":"mranuran.com"}]}';
// Map<String,dynamic> cardMap = json.decode(jsonString);
// EgluCard egluCard = EgluCard.fromJson(cardMap);
// print(egluCard.actions[0].label);
var jsonString = json.encode(egluCard);
var trimmedString = jsonString.substring(0,jsonString.length);
print(trimmedString);
cardsDBRef.push().set(jsonString)
.then((_){
print('saved!!');
});
when I am printing the json.encode(eGluCard) then it's printing a valid json but when it's getting saved into firebase I am getting the following from firebase. It was supposed to save as key value pair but it was saved as a whole string.
"{\"isInternal\":true,\"isPublished\":true,\"title\":\"HI\",\"body\":\"World\",\"caption\":\"Awesome\",\"cardType\":\"TYPE_1\",\"images\":[\"images\"],\"expiry\":123,\"showAt\":125,\"bgColor\":\"#FFFFFF\",\"platformType\":\"IOS\",\"actions\":[{\"label\":\"This is label\",\"url\":\"mranuran.com\"}]}"
what can be wrong in this approach? below are my model classed and their generated serializer respectively
EgluCard.dart
import 'card_type.dart';
import 'platform_type.dart';
import 'action.dart';
import 'package:json_annotation/json_annotation.dart';
part 'eglu_card.g.dart';
#JsonSerializable()
class EgluCard {
bool isInternal;
bool isPublished;
String title;
String body;
String caption;
CardType cardType;
List<String> images;
int expiry;
int showAt;
String bgColor;
PlatformType platformType;
List<Action> actions;
EgluCard(this.isInternal,this.isPublished,this.title,this.body,this.caption,this.cardType,this.images,
this.expiry,this.showAt,this.bgColor,this.platformType,this.actions);
factory EgluCard.fromJson(Map<String, dynamic> json) => _$EgluCardFromJson(json);
Map<String, dynamic> toJson() => _$EgluCardToJson(this);
}
EgluCard Serializer
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'eglu_card.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
EgluCard _$EgluCardFromJson(Map<String, dynamic> json) {
return EgluCard(
json['isInternal'] as bool,
json['isPublished'] as bool,
json['title'] as String,
json['body'] as String,
json['caption'] as String,
_$enumDecodeNullable(_$CardTypeEnumMap, json['cardType']),
(json['images'] as List)?.map((e) => e as String)?.toList(),
json['expiry'] as int,
json['showAt'] as int,
json['bgColor'] as String,
_$enumDecodeNullable(_$PlatformTypeEnumMap, json['platformType']),
(json['actions'] as List)
?.map((e) =>
e == null ? null : Action.fromJson(e as Map<String, dynamic>))
?.toList());
}
Map<String, dynamic> _$EgluCardToJson(EgluCard instance) => <String, dynamic>{
'isInternal': instance.isInternal,
'isPublished': instance.isPublished,
'title': instance.title,
'body': instance.body,
'caption': instance.caption,
'cardType': _$CardTypeEnumMap[instance.cardType],
'images': instance.images,
'expiry': instance.expiry,
'showAt': instance.showAt,
'bgColor': instance.bgColor,
'platformType': _$PlatformTypeEnumMap[instance.platformType],
'actions': instance.actions
};
T _$enumDecode<T>(Map<T, dynamic> enumValues, dynamic source) {
if (source == null) {
throw ArgumentError('A value must be provided. Supported values: '
'${enumValues.values.join(', ')}');
}
return enumValues.entries
.singleWhere((e) => e.value == source,
orElse: () => throw ArgumentError(
'`$source` is not one of the supported values: '
'${enumValues.values.join(', ')}'))
.key;
}
T _$enumDecodeNullable<T>(Map<T, dynamic> enumValues, dynamic source) {
if (source == null) {
return null;
}
return _$enumDecode<T>(enumValues, source);
}
const _$CardTypeEnumMap = <CardType, dynamic>{CardType.TYPE_1: 'TYPE_1'};
const _$PlatformTypeEnumMap = <PlatformType, dynamic>{
PlatformType.ANDROID: 'ANDROID',
PlatformType.IOS: 'IOS',
PlatformType.ANDROID_THING: 'ANDROID_THING',
PlatformType.ANY: 'ANY'
};
Action.dart
import 'package:json_annotation/json_annotation.dart';
part 'action.g.dart';
#JsonSerializable()
class Action {
String label;
String url;
Action(this.label,this.url);
factory Action.fromJson(Map<String, dynamic> json) => _$ActionFromJson(json);
Map<String, dynamic> toJson() => _$ActionToJson(this);
}
Action Serializer
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'action.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Action _$ActionFromJson(Map<String, dynamic> json) {
return Action(json['label'] as String, json['url'] as String);
}
Map<String, dynamic> _$ActionToJson(Action instance) =>
<String, dynamic>{'label': instance.label, 'url': instance.url};
PlatformType and CardType are enums
Okay turns out I have to decode and encoded string before passing it to firebase.
So code to save the model class to firebase will be like this:
List<Action> actions = [];
actions.add(new Action('This is label', 'mranuran.com'));
EgluCard egluCard = new EgluCard(true, true, "HI", "World", "Awesome",CardType.TYPE_1 , ["images"], 123, 125, "#FFFFFF", PlatformType.IOS, actions);
var jsonString = json.encode(egluCard);
print(json.decode(jsonString));
cardsDBRef.push().set(json.decode(jsonString))
.then((_){
print('saved!!');
});