I want to post servieces data and packages data in post type api.
But I dont know how to send multiple services and multiple packages data in this type of json.
{
"branch_uuid": "2e62af28-3a9e-4309-bff4-66e74a322c5x",
"date": "2021-09-17",
"time": "11:00",
"services": [
{
"uuid": "63e1e00f-5af4-4ae2-9fca-4f3e0a9cd420",
"staff_uuid": "e29b9e3a-0d28-472a-ae27-c372b4ca1a89"
},
{
"uuid": "674d978a-0d88-4374-b915-9c42630f6aa7",
"staff_uuid": "3a211faf-938b-4220-8288-dfe860ed3b13"
}
],
"packages": [
{
"uuid": "ba88f33f-9a48-4cf1-b55c-45ccce6e7253",
"services": [
{
"uuid": "63e1e00f-5af4-4ae2-9fca-4f3e0a9cd420"
},
{
"uuid": "674d978a-0d88-4374-b915-9c42630f6aa7"
}
]
},
{
"uuid": "4de60d34-526b-4ac2-9df4-34876f58e39d",
"services": [
{
"uuid": "674d978a-0d88-4374-b915-9c42630f6aa7"
}
]
}
],
"remarks": "",
"tax": 100,
"discount": 400,
"coupon": "SALE100"
}
I send data in post api in flutter code like this
var bookingData = {
"branch_uuid": widget.branchListData['uuid'].toString(),
"date":"${widget.selectedDate}-${widget.selectedMonthInNum}-${widget.selectedYear}",
"time": "${widget.choosedTime}"
"services": // what and how to do here,
"packages": // what and how to do here
};
You can make model classes and write toJson inside models to do this task :
class Data {
String branchUuid;
String date;
String time;
List<Services> services;
List<Packages> packages;
String remarks;
int tax;
int discount;
String coupon;
Data(
{this.branchUuid,
this.date,
this.time,
this.services,
this.packages,
this.remarks,
this.tax,
this.discount,
this.coupon});
Data.fromJson(Map<String, dynamic> json) {
branchUuid = json['branch_uuid'];
date = json['date'];
time = json['time'];
if (json['services'] != null) {
services = new List<Services>();
json['services'].forEach((v) {
services.add(new Services.fromJson(v));
});
}
if (json['packages'] != null) {
packages = new List<Packages>();
json['packages'].forEach((v) {
packages.add(new Packages.fromJson(v));
});
}
remarks = json['remarks'];
tax = json['tax'];
discount = json['discount'];
coupon = json['coupon'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['branch_uuid'] = this.branchUuid;
data['date'] = this.date;
data['time'] = this.time;
if (this.services != null) {
data['services'] = this.services.map((v) => v.toJson()).toList();
}
if (this.packages != null) {
data['packages'] = this.packages.map((v) => v.toJson()).toList();
}
data['remarks'] = this.remarks;
data['tax'] = this.tax;
data['discount'] = this.discount;
data['coupon'] = this.coupon;
return data;
}
}
class Services {
String uuid;
String staffUuid;
Services({this.uuid, this.staffUuid});
Services.fromJson(Map<String, dynamic> json) {
uuid = json['uuid'];
staffUuid = json['staff_uuid'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['uuid'] = this.uuid;
data['staff_uuid'] = this.staffUuid;
return data;
}
}
class Packages {
String uuid;
List<Services> services;
Packages({this.uuid, this.services});
Packages.fromJson(Map<String, dynamic> json) {
uuid = json['uuid'];
if (json['services'] != null) {
services = new List<Services>();
json['services'].forEach((v) {
services.add(new Services.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['uuid'] = this.uuid;
if (this.services != null) {
data['services'] = this.services.map((v) => v.toJson()).toList();
}
return data;
}
}
class Services {
String uuid;
Services({this.uuid});
Services.fromJson(Map<String, dynamic> json) {
uuid = json['uuid'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['uuid'] = this.uuid;
return data;
}
}
these classes can be your models and you should use Data class like this:
List<Services> services = [Service(uuid:"63e1e00f-5af4-4ae2-9fca-4f3e0a9cd420",staff_uuid :"3a211faf-938b-4220-8288-dfe860ed3b13"),Service(uuid:"674d978a-0d88-4374-b915-9c42630f6aa7",staff_uuid : "3a211faf-938b-4220-8288-dfe860ed3b13"), ];
List<Packages> packages = [Packages(uuid : "ba88f33f-9a48-4cf1-b55c-45ccce6e7253",[Service(uuid:"63e1e00f-5af4-4ae2-9fca-4f3e0a9cd420",staff_uuid :"3a211faf-938b-4220-8288-dfe860ed3b13")]),Packages(uuid : "ba88f33f-9a48-4cf1-b55c-45ccce6e7253",[Service(uuid:"63e1e00f-5af4-4ae2-9fca-4f3e0a9cd420",staff_uuid :"3a211faf-938b-4220-8288-dfe860ed3b13")]), ];
Map<String, dynamic> map = Data(
branch_uuid : widget.branchListData['uuid'].toString(),
date : "${widget.selectedDate}-${widget.selectedMonthInNum}-${widget.selectedYear}",
time: "${widget.choosedTime}",
services : services,
packages : packages,
).toJson();
and for packages do like services.
import 'dart:convert';
SendDataModel sendDataModelFromJson(String str) => SendDataModel.fromJson(json.decode(str));
String sendDataModelToJson(SendDataModel data) => json.encode(data.toJson());
class SendDataModel {
SendDataModel({
this.branchUuid,
this.date,
this.time,
this.services,
this.packages,
this.remarks,
this.tax,
this.discount,
this.coupon,
});
String? branchUuid;
String? date;
String? time;
List<SendDataModelService>? services;
List<Package>? packages;
String? remarks;
int? tax;
int? discount;
String? coupon;
factory SendDataModel.fromJson(Map<String, dynamic> json) => SendDataModel(
branchUuid: json["branch_uuid"] == null ? null : json["branch_uuid"],
date: json["date"] == null ? null : json["date"],
time: json["time"] == null ? null : json["time"],
services: json["services"] == null ? null : List<SendDataModelService>.from(json["services"].map((x) => SendDataModelService.fromJson(x))),
packages: json["packages"] == null ? null : List<Package>.from(json["packages"].map((x) => Package.fromJson(x))),
remarks: json["remarks"] == null ? null : json["remarks"],
tax: json["tax"] == null ? null : json["tax"],
discount: json["discount"] == null ? null : json["discount"],
coupon: json["coupon"] == null ? null : json["coupon"],
);
Map<String, dynamic> toJson() => {
"branch_uuid": branchUuid == null ? null : branchUuid,
"date": date == null ? null : date,
"time": time == null ? null : time,
"services": services == null ? null : List<dynamic>.from(services!.map((x) => x.toJson())),
"packages": packages == null ? null : List<dynamic>.from(packages!.map((x) => x.toJson())),
"remarks": remarks == null ? null : remarks,
"tax": tax == null ? null : tax,
"discount": discount == null ? null : discount,
"coupon": coupon == null ? null : coupon,
};
}
class Package {
Package({
this.uuid,
this.services,
});
String? uuid;
List<PackageService>? services;
factory Package.fromJson(Map<String, dynamic> json) => Package(
uuid: json["uuid"] == null ? null : json["uuid"],
services: json["services"] == null ? null : List<PackageService>.from(json["services"].map((x) => PackageService.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"uuid": uuid == null ? null : uuid,
"services": services == null ? null : List<dynamic>.from(services!.map((x) => x.toJson())),
};
}
class PackageService {
PackageService({
this.uuid,
});
String? uuid;
factory PackageService.fromJson(Map<String, dynamic> json) => PackageService(
uuid: json["uuid"] == null ? null : json["uuid"],
);
Map<String, dynamic> toJson() => {
"uuid": uuid == null ? null : uuid,
};
}
class SendDataModelService {
SendDataModelService({
this.uuid,
this.staffUuid,
});
String? uuid;
String? staffUuid;
factory SendDataModelService.fromJson(Map<String, dynamic> json) => SendDataModelService(
uuid: json["uuid"] == null ? null : json["uuid"],
staffUuid: json["staff_uuid"] == null ? null : json["staff_uuid"],
);
Map<String, dynamic> toJson() => {
"uuid": uuid == null ? null : uuid,
"staff_uuid": staffUuid == null ? null : staffUuid,
};
}
First create send data model.
late SendDataModel data;
data = SendDataModel(
branchUuid: "branchUuid",
coupon: "coupon",
date: "date",
time: "time",
discount: 12345,
remarks: "remarks",
tax: 12345,
);
List<SendDataModelService>? sendDataModelServiceList = [];
// If you have an expandable list
// If you keep the data as List<SendDataModelService> while keeping the data initially, you can make data.service = yourList without the need for ".add".
sendDataModelServiceList.add(SendDataModelService(uuid: "uuid", staffUuid: "staffUuid"));
data.services = sendDataModelServiceList;
List<Package> sendDataModelPackageList = [];
List<PackageService> tmpPackageServiceList = [];
tmpPackageServiceList.add(PackageService(uuid: "uuid"));
sendDataModelPackageList.add(Package(uuid: "uuid", services: tmpPackageServiceList));
// The important thing here is to keep your data in the model type that was created when you first created it, so your data will not be mixed.
var encodedData = jsonEncode(data);
if you want to send it via formData.
formData: FormData.fromMap({
"formDataKey": jsonEncode({
data,
}),
}),
First of all, you need to create model class for those json object.
import 'dart:convert';
BookingData bookingDataFromJson(String str) => BookingData.fromJson(json.decode(str));
String bookingDataToJson(BookingData data) => json.encode(data.toJson());
class BookingData {
BookingData({
this.branchUuid,
this.date,
this.time,
this.services,
this.packages,
this.remarks,
this.tax,
this.discount,
this.coupon,
});
String branchUuid;
DateTime date;
String time;
List<BookingDataService> services;
List<Package> packages;
String remarks;
int tax;
int discount;
String coupon;
factory BookingData.fromJson(Map<String, dynamic> json) => BookingData(
branchUuid: json["branch_uuid"],
date: DateTime.parse(json["date"]),
time: json["time"],
services: List<BookingDataService>.from(json["services"].map((x) => BookingDataService.fromJson(x))),
packages: List<Package>.from(json["packages"].map((x) => Package.fromJson(x))),
remarks: json["remarks"],
tax: json["tax"],
discount: json["discount"],
coupon: json["coupon"],
);
Map<String, dynamic> toJson() => {
"branch_uuid": branchUuid,
"date": "${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}",
"time": time,
"services": List<dynamic>.from(services.map((x) => x.toJson())),
"packages": List<dynamic>.from(packages.map((x) => x.toJson())),
"remarks": remarks,
"tax": tax,
"discount": discount,
"coupon": coupon,
};
}
class Package {
Package({
this.uuid,
this.services,
});
String uuid;
List<PackageService> services;
factory Package.fromJson(Map<String, dynamic> json) => Package(
uuid: json["uuid"],
services: List<PackageService>.from(json["services"].map((x) => PackageService.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"uuid": uuid,
"services": List<dynamic>.from(services.map((x) => x.toJson())),
};
}
class PackageService {
PackageService({
this.uuid,
});
String uuid;
factory PackageService.fromJson(Map<String, dynamic> json) => PackageService(
uuid: json["uuid"],
);
Map<String, dynamic> toJson() => {
"uuid": uuid,
};
}
class BookingDataService {
BookingDataService({
this.uuid,
this.staffUuid,
});
String uuid;
String staffUuid;
factory BookingDataService.fromJson(Map<String, dynamic> json) => BookingDataService(
uuid: json["uuid"],
staffUuid: json["staff_uuid"],
);
Map<String, dynamic> toJson() => {
"uuid": uuid,
"staff_uuid": staffUuid,
};
}
For Api call, you get string bookingStringDataForApi:
String bookingStringDataForApi = bookingDataToJson(/*TODO pass booking model object*/)
And then post bookingStringDataForApi using formdata
Related
I’m trying to parse one object from a Json response. My response.data is of type ‘_InternalLinkedHashMap<String, dynamic>’. I would like to transform it to the type of my object. So for doing that I use the method fromJson of my class.
Class code:
import 'dart:convert';
import 'package:.../stl/store_stl.dart';
class StoreSTLModel extends StoreSTL {const StoreSTLModel({
required String storeId,
required String storeName,
required String subContextUrl,
required List<dynamic> openingEvent,
required List<dynamic> closingEvent,
}) : super(
storeId: storeId,
storeName: storeName,
subContextUrl: subContextUrl,
openingEvent: openingEvent,
closingEvent:closingEvent ,
);
Map<String, dynamic> toMap() {
return <String, dynamic>{
'storeId': storeId,
'storeName': storeName,
'subContextUrl': subContextUrl,
'openingEvent': openingEvent.toList(),
'closingEvent': closingEvent.toList(),
};
}
factory StoreSTLModel.fromMap(Map<String, dynamic> map) {
return StoreSTLModel(
storeId: map['storeId'] as String ,
storeName: map["storeName"] as String,
subContextUrl: map["subContextUrl"] as String,
openingEvent: List<dynamic>.from(map["openingEvent"] as List<dynamic>),
closingEvent: List<dynamic>.from(map["closingEvent"] as List<dynamic>),
);
}
String toJson() => json.encode(toMap());
factory StoreSTLModel.fromJson(String source) => StoreSTLModel.fromMap(json.decode(source) as Map<String, dynamic>);
}
the code of my request is as follow: (I’m using Dio package)
import 'package:.../app_constants.dart';
import 'package:dio/dio.dart';
import 'package:...stl/store_stl_model.dart';
class RemoteStoreSTLDataSource {
static dynamic apiSTLData;
static late final urlApiSTL = AppConstants.urlApiSTL;
//get store from api STL (for now store id is hardcode)
Future<StoreSTLModel> getStoreFromSTL() async{
if(apiSTLData == null){
apiSTLData = {};
try{
Response? response = await Dio().get(
urlApiSTL,
);
apiSTLData = response.data;
print('apiSTLData type response.data ${ apiSTLData.runtimeType}');
//prints: apiSTLData type response.data _InternalLinkedHashMap<String, dynamic>
}on Exception {
null;
print('apiSTLData Exception');
}
}
print('apiSTLData type response.data[store] ${apiSTLData['store'].runtimeType}');
//prints: apiSTLData type response.data[store] _InternalLinkedHashMap<String, dynamic>
return StoreSTLModel.fromJson(apiSTLData['store']);
}
}
when I try to run, I’m having the error:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
so I don’t understand why it is not being parsed. and I don’t understand why the response is of this type ‘_InternalLinkedHashMap<String, dynamic>’ I'm a beginner in Dart. Could you please help me to understand. Thanks in advance :)
{
"store": {
"storeId": "30264",
"storeName": "xxxxx",
"subContextUrl": "hxxxu-xxxxx",
"type": "STORE",
"address": {
"label": null,
"zipcode": "xxxx",
"city": "xxxx",
"countryCode": "xxxx",
"lines": [
"xxxxxxxx",
""
]
},
"openingEvent": [],
"closingEvent": [],
"dayHours": {
"day": "THURSDAY",
"morningOpeningHour": "08:30:00",
"morningClosingHour": null,
"afternoonOpeningHour": null,
"afternoonClosingHour": "20:00:00"
},
"driveHours": {
"timezone": "xxxxxx",
"openHourList": [
{
"day": "MONDAY",
"morningOpeningHour": "08:30:00",
"morningClosingHour": null,
"afternoonOpeningHour": null,
"afternoonClosingHour": "20:00:00"
},
{
"day": "SUNDAY",
"morningOpeningHour": null,
"morningClosingHour": null,
"afternoonOpeningHour": null,
"afternoonClosingHour": null
}
]
},
"eservices": [
{
"website": "serviceWebsite - to be defined",
"linkTitle": null,
"linklabel": null,
"serviceId": 2,
"serviceName": "xxxxxx"
},
{
"website": "serviceWebsite - to be defined",
"linkTitle": null,
"linklabel": null,
"serviceId": 4,
"serviceName": "xxxxxx"
},
{
"website": "serviceWebsite - to be defined",
"linkTitle": null,
"linklabel": null,
"serviceId": 39,
"serviceName": "xxxxx"
}
],
"services": [
"xxxxxx",
"xxxxx",
"xxxxxxx"
],
"additionalStoreInfo": {
"status": "xxxxx",
"commercialSignLabel": "xxxxx"
}
}
}
This is model class
import 'dart:convert';
class StoreSTLModel {
StoreSTLModel({
required this.store,
});
final Store store;
factory StoreSTLModel.fromJson(String str) => StoreSTLModel.fromMap(json.decode(str));
factory StoreSTLModel.fromMap(Map<String, dynamic> json) => StoreSTLModel(
store: Store.fromMap(json["store"]),
);
Map<String, dynamic> toMap() => {
"store": store.toMap(),
};
}
class Store {
Store({
required this.storeId,
required this.storeName,
required this.subContextUrl,
required this.type,
required this.address,
required this.openingEvent,
required this.closingEvent,
required this.dayHours,
required this.driveHours,
required this.eservices,
required this.services,
required this.additionalStoreInfo,
});
final String storeId;
final String storeName;
final String subContextUrl;
final String type;
final Address address;
final List<dynamic> openingEvent;
final List<dynamic> closingEvent;
final DayHours dayHours;
final DriveHours driveHours;
final List<Eservice> eservices;
final List<String> services;
final AdditionalStoreInfo additionalStoreInfo;
factory Store.fromMap(Map<String, dynamic> json) => Store(
storeId: json["storeId"],
storeName: json["storeName"],
subContextUrl: json["subContextUrl"],
type: json["type"],
address: Address.fromMap(json["address"]),
openingEvent: List<dynamic>.from(json["openingEvent"].map((x) => x)),
closingEvent: List<dynamic>.from(json["closingEvent"].map((x) => x)),
dayHours: DayHours.fromMap(json["dayHours"]),
driveHours: DriveHours.fromMap(json["driveHours"]),
eservices: List<Eservice>.from(json["eservices"].map((x) => Eservice.fromMap(x))),
services: List<String>.from(json["services"].map((x) => x)),
additionalStoreInfo: AdditionalStoreInfo.fromMap(json["additionalStoreInfo"]),
);
Map<String, dynamic> toMap() => {
"storeId": storeId,
"storeName": storeName,
"subContextUrl": subContextUrl,
"type": type,
"address": address.toMap(),
"openingEvent": List<dynamic>.from(openingEvent.map((x) => x)),
"closingEvent": List<dynamic>.from(closingEvent.map((x) => x)),
"dayHours": dayHours.toMap(),
"driveHours": driveHours.toMap(),
"eservices": List<dynamic>.from(eservices.map((x) => x.toMap())),
"services": List<dynamic>.from(services.map((x) => x)),
"additionalStoreInfo": additionalStoreInfo.toMap(),
};
}
class AdditionalStoreInfo {
AdditionalStoreInfo({
required this.status,
required this.commercialSignLabel,
});
final String status;
final String commercialSignLabel;
factory AdditionalStoreInfo.fromMap(Map<String, dynamic> json) => AdditionalStoreInfo(
status: json["status"],
commercialSignLabel: json["commercialSignLabel"],
);
Map<String, dynamic> toMap() => {
"status": status,
"commercialSignLabel": commercialSignLabel,
};
}
class Address {
Address({
required this.label,
required this.zipcode,
required this.city,
required this.countryCode,
required this.lines,
});
final dynamic label;
final String zipcode;
final String city;
final String countryCode;
final List<String> lines;
factory Address.fromMap(Map<String, dynamic> json) => Address(
label: json["label"],
zipcode: json["zipcode"],
city: json["city"],
countryCode: json["countryCode"],
lines: List<String>.from(json["lines"].map((x) => x)),
);
Map<String, dynamic> toMap() => {
"label": label,
"zipcode": zipcode,
"city": city,
"countryCode": countryCode,
"lines": List<dynamic>.from(lines.map((x) => x)),
};
}
class DayHours {
DayHours({
required this.day,
required this.morningOpeningHour,
required this.morningClosingHour,
required this.afternoonOpeningHour,
required this.afternoonClosingHour,
});
final String day;
final String morningOpeningHour;
final dynamic morningClosingHour;
final dynamic afternoonOpeningHour;
final String afternoonClosingHour;
factory DayHours.fromMap(Map<String, dynamic> json) => DayHours(
day: json["day"],
morningOpeningHour: json["morningOpeningHour"],
morningClosingHour: json["morningClosingHour"],
afternoonOpeningHour: json["afternoonOpeningHour"],
afternoonClosingHour: json["afternoonClosingHour"],
);
Map<String, dynamic> toMap() => {
"day": day,
"morningOpeningHour": morningOpeningHour,
"morningClosingHour": morningClosingHour,
"afternoonOpeningHour": afternoonOpeningHour,
"afternoonClosingHour": afternoonClosingHour,
};
}
class DriveHours {
DriveHours({
required this.timezone,
required this.openHourList,
});
final String timezone;
final List<DayHours> openHourList;
factory DriveHours.fromMap(Map<String, dynamic> json) => DriveHours(
timezone: json["timezone"],
openHourList: List<DayHours>.from(json["openHourList"].map((x) => DayHours.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"timezone": timezone,
"openHourList": List<dynamic>.from(openHourList.map((x) => x.toMap())),
};
}
class Eservice {
Eservice({
required this.website,
required this.linkTitle,
required this.linklabel,
required this.serviceId,
required this.serviceName,
});
final String website;
final dynamic linkTitle;
final dynamic linklabel;
final int serviceId;
final String serviceName;
factory Eservice.fromMap(Map<String, dynamic> json) => Eservice(
website: json["website"],
linkTitle: json["linkTitle"],
linklabel: json["linklabel"],
serviceId: json["serviceId"],
serviceName: json["serviceName"],
);
Map<String, dynamic> toMap() => {
"website": website,
"linkTitle": linkTitle,
"linklabel": linklabel,
"serviceId": serviceId,
"serviceName": serviceName,
};
}
This is Dio class
import 'dart:convert';
import 'package:.../app_constants.dart';
import 'package:dio/dio.dart';
import 'package:...stl/store_stl_model.dart';
class RemoteStoreSTLDataSource {
static dynamic apiSTLData;
static late final urlApiSTL = AppConstants.urlApiSTL;
Future<StoreSTLModel> getStoreFromSTL() async{
if(apiSTLData == null){
apiSTLData = {};
try{
final response = await Dio().get(
urlApiSTL,
);
apiSTLData = response.data;
if (response.statusCode == 200) {
//Try them, one of them will work.
return StoreSTLModel.fromMap(apiSTLData);
return StoreSTLModel.fromJson(apiSTLData);
} else {
throw Exception("404 error");
}
} on DioError catch (e) {
return Future.error(e.message);
}
}
}
}
Try this.
How to create class model in flutter if List Array of Array have 2 type data
Example
"value" : [["Water Melon", "Apple", 10, 23]]
#JsonSerializable()
class GetReportBodyData {
String type;
String title;
List<String> headers;
List<List<int>> value = new List<List<int>>();
GetReportBodyData({this.type, this.title, this.headers, this.value});
#override
String toString() {
return 'GetReportBodyData{type: $type, title: $title, header: $headers, value: $value}';
}
factory GetReportBodyData.fromJson(Map<String, dynamic> json) {
return GetReportBodyData(
type: json["type"],
title: json["title"],
headers: json["header"] != null ? List<String>.from(json["header"]) :[],
value: List<List<int>>.from(json["value"])
);
}
Map<String, dynamic>toJson() => {
"type": type,
"title": title,
"header": headers,
"value": value
};
}
class example {
List<List> value;
example({this.value});
example.fromJson(Map<String, dynamic> json) {
if (json['value'] != null) {
value = new List<List>();
json['value'].forEach((v) { value.add(new List.fromJson(v)); });
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.value != null) {
data['value'] = this.value.map((v) => v.toJson()).toList();
}
return data;
}
}
class Value {
Value({});
Value.fromJson(Map<String, dynamic> json) {
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
return data;
}
I am getting error as 'List<dynamic>' is not a subtype of type 'List<options>'
Here is my code:
List<SampleModel> cartList = allStores.keys
// var allStores = response.data['data'];
// var cartList = allStores.keys
.map((name) => SampleModel(
sname: name,
selected: false,
storeList: allStores[name].map((name) => SampleModel(
sname: name,
selected: false,
storeList: allStores[name].map<Store>((store) => Store(
id: store['id'],
selected: false,
stid: store['stid'],
product: Products(
id: store['product']['id'],
type: store['product']['type_id'],
options: store['product']['options'].length > 0 ? store['product']['options'].map((f) => Options.fromJson(f)).toList() : null
),
)
).toList(),
)
).toList();
Model:
class SampleModel {
String sname;
bool selected;
List<Store> storeList;
SampleModel({this.sname, this.selected, this.storeList});
SampleModel.fromJson(Map<String, dynamic> json) {
sname = json['sname'];
selected = json['selected'];
storeList = List<Store>.from(json["storeList"].map((x) => Store.fromJson(x)));
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['sname'] = this.sname;
data['selected'] = this.selected;
data['storeList'] = List<dynamic>.from(storeList.map((x) => x.toJson()));
return data;
}
}
class Store {
int id;
int stid;
Store({
this.id,
this.stid,
});
Store.fromJson(Map<String, dynamic> json) {
id = json['id'];
stid = json['cart_id'];
selected = json['selected'];
quantity = json['quantity'];
product = Products.fromJson(json["product"]);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['cart_id'] = this.stid;
data['product'] = product.toJson();
return data;
}
}
class Products {
int id;
String name;
List<Options> options;
Products({
this.id,
this.name,
this.options,
});
Products.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
type = json['type'];
options = json["options"] == null
? null
: List<Options>.from(
json["options"].map((x) => Options.fromJson(x)));
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['options'] = options == null
? null
: List<dynamic>.from(options.map((x) => x.toJson()));
return data;
}
}
}
class Options {
int id;
String name;
Options({
this.id,
this.name,
});
Options.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}
Here is my sample json
{
"sta1": [{
"id": 948,
"sid": 67,
"product": {
"id": 123,
"name": "tesssss",
"Options": [{
"id": 1,
"name": "asdasd"
}, {
"id": 2,
"name": "wer",
"seq": 1
}]
}
}],
"sta2": [{
"id": 948,
"sid": 67,
"product": {
"id": 123,
"name": "tesssss",
"Options": [{
"id": 1,
"name": "asdasd"
}, {
"id": 2,
"name": "wer",
"seq": 1
}]
}
}]
}
Everything works fine but options is not mapping, it shows error as
'List' is not a subtype of type 'List'
What am I missing here? Its an object and options is an array so I need to have it as a list in front end
everything i can able to loop but one thing options is not working
getting error in following line
options: store['product']['options'].length > 0 ? store['product']['options'].map((f) => Options.fromJson(f)).toList() : null
I had a similar problem, I think that Flutter lost the reference of type of object, but I can fix using like this in your fromJson:
options = json["options"] == null
? null
: List<Options>.from(
json["options"].map<Option>((x) => Options.fromJson(x.cast<String, dynamic>())));
}
Casting the map and using the cast in your map object.
I hope that can help you too.
As a learner, I'm trying to build my first project, however I'm facing a problem trying to parse this json object
{
"_id": 14080,
"ankamaId": 14080,
"name": "Amulette Séculaire",
"level": 200,
"type": "Amulette",
"imgUrl": "https://s.ankama.com/www/static.ankama.com/dofus-touch/www/game/items/200/1230.png",
"url": "https://www.dofus-touch.com/fr/mmorpg/encyclopedie/equipements/14080-amulette-seculaire",
"description": "Finalement, le secteur de la bijouterie n'a pas tellement évolué ces cent dernières années.",
"statistics": [
{
"Vitalité": {
"min": 251,
"max": 300
}
},
{
"Intelligence": {
"min": 61,
"max": 80
}
},
{
"Agilité": {
"min": 16,
"max": 25
}
},
{
"Sagesse": {
"min": 31,
"max": 40
}
},
{
"PA": {
"min": 1,
"max": null
}
},
{
"Prospection": {
"min": 16,
"max": 20
}
},
{
"Dommages Feu": {
"min": 8,
"max": 12
}
},
{
"Dommages Air": {
"min": 8,
"max": 12
}
},
{
"% Résistance Neutre": {
"min": 6,
"max": 8
}
},
{
"% Résistance Feu": {
"min": 6,
"max": 8
}
},
{
"Résistance Critiques": {
"min": 11,
"max": 15
}
}
],
}
Below is the way I'm parsing the object.
item_model.dart
#JsonSerializable(explicitToJson: true)
class Item {
int id;
int ankamaId;
String name;
int level;
String type;
String imgUrl;
String url;
String description;
List<Map<String, Statistic>> statistics;
Item({
this.id,
this.ankamaId,
this.name,
this.level,
this.type,
this.imgUrl,
this.url,
this.description,
this.statistics,
});
factory Item.fromJson(Map<String,dynamic> data) => _$ItemFromJson(data);
Map<String,dynamic> toJson() => _$ItemToJson ( this);
}
#JsonSerializable()
class Statistic {
int max;
int min;
Statistic({
this.min,
this.max,
});
factory Statistic.fromJson(Map<String,dynamic> data) => _$StatisticFromJson(data);
Map<String,dynamic> toJson() => _$StatisticToJson(this);
}
item_model.g.dart
Item _$ItemFromJson(Map<String, dynamic> json) {
return Item(
id: json['id'] as int,
ankamaId: json['ankamaId'] as int,
name: json['name'] as String,
level: json['level'] as int,
type: json['type'] as String,
imgUrl: json['imgUrl'] as String,
url: json['url'] as String,
description: json['description'] as String,
statistics: (json['statistics'] as List)
?.map((e) => (e as Map<String, dynamic>)?.map(
(k, e) => MapEntry(
k,
e == null
? null
: Statistic.fromJson(e as Map<String, dynamic>)),
))
?.toList(),
);
}
Map<String, dynamic> _$ItemToJson(Item instance) => <String, dynamic>{
'id': instance.id,
'ankamaId': instance.ankamaId,
'name': instance.name,
'level': instance.level,
'type': instance.type,
'imgUrl': instance.imgUrl,
'url': instance.url,
'description': instance.description,
'statistics': instance.statistics
?.map((e) => e?.map((k, e) => MapEntry(k, e?.toJson())))
?.toList(),
};
Statistic _$StatisticFromJson(Map<String, dynamic> json) {
return Statistic(
min: json['min'] as int,
max: json['max'] as int,
);
}
Map<String, dynamic> _$StatisticToJson(Statistic instance) => <String, dynamic>{
'max': instance.max,
'min': instance.min,
};
Basically, what I want to do is show in a listview the max, and the min attribute of each element of the statistics list.
Thank you so much in advance.
Make sure the order of the model class, is same as that of the Api data. Also the data types used is compatible. Here errors can creep in. I don't see any other issues in the code
You can use this site for get your model from json, just copy and past
There's a brilliant tool (not the one that other ppl linked) that creates dart code for your JSON:
https://javiercbk.github.io/json_to_dart/
It helped me a ton when working with different APIs.
The dart code in your case would be this:
class myJson {
int iId;
int ankamaId;
String name;
int level;
String type;
String imgUrl;
String url;
String description;
List<Statistics> statistics;
myJson(
{this.iId,
this.ankamaId,
this.name,
this.level,
this.type,
this.imgUrl,
this.url,
this.description,
this.statistics});
myJson.fromJson(Map<String, dynamic> json) {
iId = json['_id'];
ankamaId = json['ankamaId'];
name = json['name'];
level = json['level'];
type = json['type'];
imgUrl = json['imgUrl'];
url = json['url'];
description = json['description'];
if (json['statistics'] != null) {
statistics = new List<Statistics>();
json['statistics'].forEach((v) {
statistics.add(new Statistics.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['_id'] = this.iId;
data['ankamaId'] = this.ankamaId;
data['name'] = this.name;
data['level'] = this.level;
data['type'] = this.type;
data['imgUrl'] = this.imgUrl;
data['url'] = this.url;
data['description'] = this.description;
if (this.statistics != null) {
data['statistics'] = this.statistics.map((v) => v.toJson()).toList();
}
return data;
}
}
class Statistics {
Vitalit vitalit;
Vitalit intelligence;
Vitalit agilit;
Vitalit sagesse;
PA pA;
Vitalit prospection;
Vitalit dommagesFeu;
Vitalit dommagesAir;
Vitalit rSistanceNeutre;
Vitalit rSistanceFeu;
Vitalit rSistanceCritiques;
Statistics(
{this.vitalit,
this.intelligence,
this.agilit,
this.sagesse,
this.pA,
this.prospection,
this.dommagesFeu,
this.dommagesAir,
this.rSistanceNeutre,
this.rSistanceFeu,
this.rSistanceCritiques});
Statistics.fromJson(Map<String, dynamic> json) {
vitalit = json['Vitalité'] != null
? new Vitalit.fromJson(json['Vitalité'])
: null;
intelligence = json['Intelligence'] != null
? new Vitalit.fromJson(json['Intelligence'])
: null;
agilit =
json['Agilité'] != null ? new Vitalit.fromJson(json['Agilité']) : null;
sagesse =
json['Sagesse'] != null ? new Vitalit.fromJson(json['Sagesse']) : null;
pA = json['PA'] != null ? new PA.fromJson(json['PA']) : null;
prospection = json['Prospection'] != null
? new Vitalit.fromJson(json['Prospection'])
: null;
dommagesFeu = json['Dommages Feu'] != null
? new Vitalit.fromJson(json['Dommages Feu'])
: null;
dommagesAir = json['Dommages Air'] != null
? new Vitalit.fromJson(json['Dommages Air'])
: null;
rSistanceNeutre = json['% Résistance Neutre'] != null
? new Vitalit.fromJson(json['% Résistance Neutre'])
: null;
rSistanceFeu = json['% Résistance Feu'] != null
? new Vitalit.fromJson(json['% Résistance Feu'])
: null;
rSistanceCritiques = json['Résistance Critiques'] != null
? new Vitalit.fromJson(json['Résistance Critiques'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.vitalit != null) {
data['Vitalité'] = this.vitalit.toJson();
}
if (this.intelligence != null) {
data['Intelligence'] = this.intelligence.toJson();
}
if (this.agilit != null) {
data['Agilité'] = this.agilit.toJson();
}
if (this.sagesse != null) {
data['Sagesse'] = this.sagesse.toJson();
}
if (this.pA != null) {
data['PA'] = this.pA.toJson();
}
if (this.prospection != null) {
data['Prospection'] = this.prospection.toJson();
}
if (this.dommagesFeu != null) {
data['Dommages Feu'] = this.dommagesFeu.toJson();
}
if (this.dommagesAir != null) {
data['Dommages Air'] = this.dommagesAir.toJson();
}
if (this.rSistanceNeutre != null) {
data['% Résistance Neutre'] = this.rSistanceNeutre.toJson();
}
if (this.rSistanceFeu != null) {
data['% Résistance Feu'] = this.rSistanceFeu.toJson();
}
if (this.rSistanceCritiques != null) {
data['Résistance Critiques'] = this.rSistanceCritiques.toJson();
}
return data;
}
}
class Vitalit {
int min;
int max;
Vitalit({this.min, this.max});
Vitalit.fromJson(Map<String, dynamic> json) {
min = json['min'];
max = json['max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['min'] = this.min;
data['max'] = this.max;
return data;
}
}
class PA {
int min;
Null max;
PA({this.min, this.max});
PA.fromJson(Map<String, dynamic> json) {
min = json['min'];
max = json['max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['min'] = this.min;
data['max'] = this.max;
return data;
}
}
You can use this tool which you just provide it with the JSON message and it will give you a class with all the variables and two function by which can parse the JSON message to the object or vice versa.
Steps:
insert a JSON message to the tool and give the class a name (don't forget to choose dart as the language)
create a new dart file and paste the class from the tool (let's assume the class name is Item)
Call final item = itemFromJson(jsonString); for parsing the JSON to the new object
Which then you can access the variables by via e.g. item.id
Edit:
so for your code, it will be:
item_model.dart
// To parse this JSON data, do
//
// final item = itemFromJson(jsonString);
import 'dart:convert';
Item itemFromJson(String str) => Item.fromJson(json.decode(str));
String itemToJson(Item data) => json.encode(data.toJson());
class Item {
Item({
this.id,
this.ankamaId,
this.name,
this.level,
this.type,
this.imgUrl,
this.url,
this.description,
this.statistics,
});
int id;
int ankamaId;
String name;
int level;
String type;
String imgUrl;
String url;
String description;
List<Map<String, Statistic>> statistics;
factory Item.fromJson(Map<String, dynamic> json) => Item(
id: json["_id"],
ankamaId: json["ankamaId"],
name: json["name"],
level: json["level"],
type: json["type"],
imgUrl: json["imgUrl"],
url: json["url"],
description: json["description"],
statistics: List<Map<String, Statistic>>.from(json["statistics"].map((x) => Map.from(x).map((k, v) => MapEntry<String, Statistic>(k, Statistic.fromJson(v))))),
);
Map<String, dynamic> toJson() => {
"_id": id,
"ankamaId": ankamaId,
"name": name,
"level": level,
"type": type,
"imgUrl": imgUrl,
"url": url,
"description": description,
"statistics": List<dynamic>.from(statistics.map((x) => Map.from(x).map((k, v) => MapEntry<String, dynamic>(k, v.toJson())))),
};
}
class Statistic {
Statistic({
this.min,
this.max,
});
int min;
int max;
factory Statistic.fromJson(Map<String, dynamic> json) => Statistic(
min: json["min"],
max: json["max"] == null ? null : json["max"],
);
Map<String, dynamic> toJson() => {
"min": min,
"max": max == null ? null : max,
};
}
You can access the variables via:
void main(){
String jsonString = "{\"_id\":14080,\"ankamaId\":14080,\"name\":\"Amulette S\u00e9culaire\",\"level\":200,\"type\":\"Amulette\",\"imgUrl\":\"https:\/\/s.ankama.com\/www\/static.ankama.com\/dofus-touch\/www\/game\/items\/200\/1230.png\",\"url\":\"https:\/\/www.dofus-touch.com\/fr\/mmorpg\/encyclopedie\/equipements\/14080-amulette-seculaire\",\"description\":\"Finalement, le secteur de la bijouterie n'a pas tellement \u00e9volu\u00e9 ces cent derni\u00e8res ann\u00e9es.\",\"statistics\":[{\"Vitalit\u00e9\":{\"min\":251,\"max\":300}},{\"Intelligence\":{\"min\":61,\"max\":80}},{\"Agilit\u00e9\":{\"min\":16,\"max\":25}},{\"Sagesse\":{\"min\":31,\"max\":40}},{\"PA\":{\"min\":1,\"max\":null}},{\"Prospection\":{\"min\":16,\"max\":20}},{\"Dommages Feu\":{\"min\":8,\"max\":12}},{\"Dommages Air\":{\"min\":8,\"max\":12}},{\"% R\u00e9sistance Neutre\":{\"min\":6,\"max\":8}},{\"% R\u00e9sistance Feu\":{\"min\":6,\"max\":8}},{\"R\u00e9sistance Critiques\":{\"min\":11,\"max\":15}}]}";
final device = deviceFromJson(jsonString);
print(device.id);
}
I am trying to loop through weather forcast form OpenWeather API.
List view is not rendered. Only loading indicator is rendered. "list" is array where i want to fetch data and display in ListView. I think there is someting wrong with model mapping. Thank you
{
"list": [
{
"dt": 1566518400,
"main": {
"temp": 14.68,
"temp_min": 14.25,
"temp_max": 14.68,
"pressure": 1029.5,
"sea_level": 1029.5,
"grnd_level": 1018.5,
"humidity": 74,
"temp_kf": 0.43
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02n"
}
],
"clouds": {
"all": 16
},
"wind": {
"speed": 2.42,
"deg": 93.981
},
"sys": {
"pod": "n"
},
"dt_txt": "2019-08-23 00:00:00"
},
Function to fetch forcast
Future<List<Forcast>> _fetchUsers() async {
http.Response response = await http.get(
'http://api.openweathermap.org/data/2.5/forecast?q=warsaw&units=metric&appid=');
if (response.statusCode == 200) {
final data = json.decode(response.body);
List<Forcast> list = data['list'].map<Forcast>((json) {
return Forcast.fromJson(json);
}).toList();
return list;
} else {
throw Exception('Failed to load internet');
}
}
Future builder
child: SizedBox(
height: 400.0,
child: FutureBuilder<List>(
future: _fetchUsers(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
return ListView(
children: snapshot.data
.map((user) => ListTile(
title: Text(user.dt),
subtitle: Text(user.temp),
))
.toList(),
);
},
),
),
Forcastt model
class Forcast {
int id;
String temp;
Forcast({
this.id,
this.temp,
});
factory Forcast.fromJson(Map<String, dynamic> json) {
print(json);
return Forcast(
id: json['dt'],
temp: json['main'].temp,
);
}
}
You can put your full json string to https://app.quicktype.io/
and you will get correct model
because json string you post in question is invalid
so I use json from demo json of https://samples.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&appid=b6907d289e10d714a6e88b30761fae22
bleow is demo Forcast structure from sample json
// To parse this JSON data, do
//
// final forcast = forcastFromJson(jsonString);
import 'dart:convert';
Forcast forcastFromJson(String str) => Forcast.fromJson(json.decode(str));
String forcastToJson(Forcast data) => json.encode(data.toJson());
class Forcast {
String cod;
double message;
int cnt;
List<ListElement> list;
City city;
Forcast({
this.cod,
this.message,
this.cnt,
this.list,
this.city,
});
factory Forcast.fromJson(Map<String, dynamic> json) => new Forcast(
cod: json["cod"],
message: json["message"].toDouble(),
cnt: json["cnt"],
list: new List<ListElement>.from(json["list"].map((x) => ListElement.fromJson(x))),
city: City.fromJson(json["city"]),
);
Map<String, dynamic> toJson() => {
"cod": cod,
"message": message,
"cnt": cnt,
"list": new List<dynamic>.from(list.map((x) => x.toJson())),
"city": city.toJson(),
};
}
class City {
int id;
String name;
Coord coord;
String country;
City({
this.id,
this.name,
this.coord,
this.country,
});
factory City.fromJson(Map<String, dynamic> json) => new City(
id: json["id"],
name: json["name"],
coord: Coord.fromJson(json["coord"]),
country: json["country"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"coord": coord.toJson(),
"country": country,
};
}
class Coord {
double lat;
double lon;
Coord({
this.lat,
this.lon,
});
factory Coord.fromJson(Map<String, dynamic> json) => new Coord(
lat: json["lat"].toDouble(),
lon: json["lon"].toDouble(),
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lon": lon,
};
}
class ListElement {
int dt;
MainClass main;
List<Weather> weather;
Clouds clouds;
Wind wind;
Sys sys;
DateTime dtTxt;
Rain rain;
Rain snow;
ListElement({
this.dt,
this.main,
this.weather,
this.clouds,
this.wind,
this.sys,
this.dtTxt,
this.rain,
this.snow,
});
factory ListElement.fromJson(Map<String, dynamic> json) => new ListElement(
dt: json["dt"],
main: MainClass.fromJson(json["main"]),
weather: new List<Weather>.from(json["weather"].map((x) => Weather.fromJson(x))),
clouds: Clouds.fromJson(json["clouds"]),
wind: Wind.fromJson(json["wind"]),
sys: Sys.fromJson(json["sys"]),
dtTxt: DateTime.parse(json["dt_txt"]),
rain: json["rain"] == null ? null : Rain.fromJson(json["rain"]),
snow: json["snow"] == null ? null : Rain.fromJson(json["snow"]),
);
Map<String, dynamic> toJson() => {
"dt": dt,
"main": main.toJson(),
"weather": new List<dynamic>.from(weather.map((x) => x.toJson())),
"clouds": clouds.toJson(),
"wind": wind.toJson(),
"sys": sys.toJson(),
"dt_txt": dtTxt.toIso8601String(),
"rain": rain == null ? null : rain.toJson(),
"snow": snow == null ? null : snow.toJson(),
};
}
class Clouds {
int all;
Clouds({
this.all,
});
factory Clouds.fromJson(Map<String, dynamic> json) => new Clouds(
all: json["all"],
);
Map<String, dynamic> toJson() => {
"all": all,
};
}
class MainClass {
double temp;
double tempMin;
double tempMax;
double pressure;
double seaLevel;
double grndLevel;
int humidity;
double tempKf;
MainClass({
this.temp,
this.tempMin,
this.tempMax,
this.pressure,
this.seaLevel,
this.grndLevel,
this.humidity,
this.tempKf,
});
factory MainClass.fromJson(Map<String, dynamic> json) => new MainClass(
temp: json["temp"].toDouble(),
tempMin: json["temp_min"].toDouble(),
tempMax: json["temp_max"].toDouble(),
pressure: json["pressure"].toDouble(),
seaLevel: json["sea_level"].toDouble(),
grndLevel: json["grnd_level"].toDouble(),
humidity: json["humidity"],
tempKf: json["temp_kf"].toDouble(),
);
Map<String, dynamic> toJson() => {
"temp": temp,
"temp_min": tempMin,
"temp_max": tempMax,
"pressure": pressure,
"sea_level": seaLevel,
"grnd_level": grndLevel,
"humidity": humidity,
"temp_kf": tempKf,
};
}
class Rain {
double the3H;
Rain({
this.the3H,
});
factory Rain.fromJson(Map<String, dynamic> json) => new Rain(
the3H: json["3h"] == null ? null : json["3h"].toDouble(),
);
Map<String, dynamic> toJson() => {
"3h": the3H == null ? null : the3H,
};
}
class Sys {
Pod pod;
Sys({
this.pod,
});
factory Sys.fromJson(Map<String, dynamic> json) => new Sys(
pod: podValues.map[json["pod"]],
);
Map<String, dynamic> toJson() => {
"pod": podValues.reverse[pod],
};
}
enum Pod { D, N }
final podValues = new EnumValues({
"d": Pod.D,
"n": Pod.N
});
class Weather {
int id;
MainEnum main;
Description description;
String icon;
Weather({
this.id,
this.main,
this.description,
this.icon,
});
factory Weather.fromJson(Map<String, dynamic> json) => new Weather(
id: json["id"],
main: mainEnumValues.map[json["main"]],
description: descriptionValues.map[json["description"]],
icon: json["icon"],
);
Map<String, dynamic> toJson() => {
"id": id,
"main": mainEnumValues.reverse[main],
"description": descriptionValues.reverse[description],
"icon": icon,
};
}
enum Description { CLEAR_SKY, BROKEN_CLOUDS, LIGHT_RAIN, MODERATE_RAIN, FEW_CLOUDS }
final descriptionValues = new EnumValues({
"broken clouds": Description.BROKEN_CLOUDS,
"clear sky": Description.CLEAR_SKY,
"few clouds": Description.FEW_CLOUDS,
"light rain": Description.LIGHT_RAIN,
"moderate rain": Description.MODERATE_RAIN
});
enum MainEnum { CLEAR, CLOUDS, RAIN }
final mainEnumValues = new EnumValues({
"Clear": MainEnum.CLEAR,
"Clouds": MainEnum.CLOUDS,
"Rain": MainEnum.RAIN
});
class Wind {
double speed;
double deg;
Wind({
this.speed,
this.deg,
});
factory Wind.fromJson(Map<String, dynamic> json) => new Wind(
speed: json["speed"].toDouble(),
deg: json["deg"].toDouble(),
);
Map<String, dynamic> toJson() => {
"speed": speed,
"deg": deg,
};
}
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}