I am getting Instance of DeviceClass instead of the actual data fields. Here is my data model:
import 'package:meta/meta.dart';
import 'dart:convert';
Device deviceFromJson(String str) => Device.fromJson(json.decode(str));
String deviceToJson(Device data) => json.encode(data.toJson());
class Device {
Device({
required this.device,
});
final DeviceClass? device;
factory Device.fromJson(Map<String, dynamic> json) => Device(
device: json["device"] == null ? null : DeviceClass.fromJson(json["device"]),
);
Map<String, dynamic> toJson() => {
"device": device == null ? null : device?.toJson(),
};
}
class DeviceClass {
DeviceClass({
required this.deviceId,
required this.publicId,
required this.companyId,
required this.company,
required this.label,
required this.mobileProviderId,
required this.mobileProvider,
required this.hologramDeviceId,
required this.hologramLinkId,
required this.firmwareVersionId,
required this.version,
required this.formattedVersion,
required this.deviceTypeId,
required this.deviceType,
required this.ipAddress,
required this.recordInterval,
required this.uploadInterval,
required this.powerMode,
required this.connectivity,
required this.connectivityClass,
required this.usersLastRecordDate,
required this.gmtLastRecordDate,
required this.battery,
required this.batteryPercentage,
required this.batteryClass,
required this.batteryIcon,
required this.signalQuality,
required this.signalQualityClass,
required this.signalQualityText,
required this.signalQualityIcon,
required this.queuedRecords,
required this.command,
required this.status,
required this.statusClass,
required this.purchaseDate,
required this.warrantyPeriod,
required this.warrantyExpires,
required this.warrantyStatus,
required this.temperatureClass,
required this.temperatureMetric,
required this.temperatureImperial,
required this.surgeProtection,
required this.totalProducts,
@required this.temperatureLowThreshold,
@required this.temperatureHighThreshold,
@required this.notes,
@required this.importId,
required this.deleted,
required this.createdBy,
required this.lastUpdatedBy,
@required this.deletedBy,
@required this.dateCreated,
required this.dateModified,
@required this.dateDeleted,
required this.scope,
required this.owner,
@required this.links,
@required this.ports,
@required this.iotDeviceTags,
@required this.entityAddresses,
@required this.availablePorts,
@required this.mobile,
});
final String deviceId;
final String publicId;
final String companyId;
final String company;
final String label;
final String mobileProviderId;
final String mobileProvider;
final String hologramDeviceId;
final String hologramLinkId;
final String firmwareVersionId;
final String version;
final String formattedVersion;
final String deviceTypeId;
final String deviceType;
final String ipAddress;
final String recordInterval;
final String uploadInterval;
final String powerMode;
final String connectivity;
final String connectivityClass;
final String usersLastRecordDate;
final DateTime? gmtLastRecordDate;
final String battery;
final String batteryPercentage;
final String batteryClass;
final String batteryIcon;
final String signalQuality;
final String signalQualityClass;
final String signalQualityText;
final String signalQualityIcon;
final String queuedRecords;
final String command;
final String status;
final String statusClass;
final DateTime? purchaseDate;
final String warrantyPeriod;
final DateTime? warrantyExpires;
final String warrantyStatus;
final String temperatureClass;
final String temperatureMetric;
final String temperatureImperial;
final String surgeProtection;
final String totalProducts;
final dynamic temperatureLowThreshold;
final dynamic temperatureHighThreshold;
final dynamic notes;
final dynamic importId;
final String deleted;
final String createdBy;
final String lastUpdatedBy;
final dynamic deletedBy;
final dynamic dateCreated;
final String dateModified;
final dynamic dateDeleted;
final String scope;
final String owner;
final DeviceLinks? links;
final List<Port>? ports;
final List<IotDeviceTag>? iotDeviceTags;
final List<EntityAddress>? entityAddresses;
final List<String>? availablePorts;
final Mobile? mobile;
factory DeviceClass.fromJson(Map<String, dynamic> json) => DeviceClass(
deviceId: json["device_id"] ?? 'null',
publicId: json["public_id"] ?? 'null',
companyId: json["company_id"] ?? 'null',
company: json["company"] ?? 'null',
label: json["label"] ?? 'null',
mobileProviderId: json["mobile_provider_id"] == null ? 'null' : json["mobile_provider_id"],
mobileProvider: json["mobile_provider"] == null ? 'null' : json["mobile_provider"],
hologramDeviceId: json["hologram_device_id"] == null ? 'null' : json["hologram_device_id"],
hologramLinkId: json["hologram_link_id"] == null ? 'null' : json["hologram_link_id"],
firmwareVersionId: json["firmware_version_id"] == null ? 'null' : json["firmware_version_id"],
version: json["version"] == null ? 'null' : json["version"],
formattedVersion: json["formatted_version"] == null ? 'null' : json["formatted_version"],
deviceTypeId: json["device_type_id"] == null ? 'null' : json["device_type_id"],
deviceType: json["device_type"] == null ? 'null' : json["device_type"],
ipAddress: json["ip_address"] == null ? 'null' : json["ip_address"],
recordInterval: json["record_interval"] == null ? 'null' : json["record_interval"],
uploadInterval: json["upload_interval"] == null ? 'null' : json["upload_interval"],
powerMode: json["power_mode"] == null ? 'null' : json["power_mode"],
connectivity: json["connectivity"] == null ? 'null' : json["connectivity"],
connectivityClass: json["connectivity_class"] == null ? 'null' : json["connectivity_class"],
usersLastRecordDate: json["users_last_record_date"] == null ? 'null' : json["users_last_record_date"],
gmtLastRecordDate: json["gmt_last_record_date"] == null ? null : DateTime.parse(json["gmt_last_record_date"]),
battery: json["battery"] == null ? 'null' : json["battery"],
batteryPercentage: json["battery_percentage"] == null ? 'null' : json["battery_percentage"],
batteryClass: json["battery_class"] == null ? 'null' : json["battery_class"],
batteryIcon: json["battery_icon"] == null ? 'null' : json["battery_icon"],
signalQuality: json["signal_quality"] == null ? 'null' : json["signal_quality"],
signalQualityClass: json["signal_quality_class"] == null ? 'null' : json["signal_quality_class"],
signalQualityText: json["signal_quality_text"] == null ? 'null' : json["signal_quality_text"],
signalQualityIcon: json["signal_quality_icon"] == null ? 'null' : json["signal_quality_icon"],
queuedRecords: json["queued_records"] == null ? 'null' : json["queued_records"],
command: json["command"] == null ? 'null' : json["command"],
status: json["status"] == null ? 'null' : json["status"],
statusClass: json["status_class"] == null ? 'null' : json["status_class"],
purchaseDate: json["purchase_date"] == null ? null : DateTime.parse(json["purchase_date"]),
warrantyPeriod: json["warranty_period"] == null ? 'null' : json["warranty_period"],
warrantyExpires: json["warranty_expires"] == null ? null : DateTime.parse(json["warranty_expires"]),
warrantyStatus: json["warranty_status"] == null ? 'null' : json["warranty_status"],
temperatureClass: json["temperature_class"] == null ? 'null' : json["temperature_class"],
temperatureMetric: json["temperature_metric"] == null ? 'null' : json["temperature_metric"],
temperatureImperial: json["temperature_imperial"] == null ? 'null' : json["temperature_imperial"],
surgeProtection: json["surge_protection"] == null ? 'null' : json["surge_protection"],
totalProducts: json["total_products"] == null ? 'null' : json["total_products"],
temperatureLowThreshold: json["temperature_low_threshold"],
temperatureHighThreshold: json["temperature_high_threshold"],
notes: json["notes"],
importId: json["import_id"],
deleted: json["deleted"] == null ? 'null' : json["deleted"],
createdBy: json["created_by"] == null ? 'null' : json["created_by"],
lastUpdatedBy: json["last_updated_by"] == null ? 'null' : json["last_updated_by"],
deletedBy: json["deleted_by"],
dateCreated: json["date_created"],
dateModified: json["date_modified"] == null ? 'null' : json["date_modified"],
dateDeleted: json["date_deleted"],
scope: json["scope"] == null ? 'null' : json["scope"],
owner: json["owner"] == null ? 'null' : json["owner"],
links: json["links"] == null ? null : DeviceLinks.fromJson(json["links"]),
ports: json["ports"] == null ? null : List<Port>.from(json["ports"].map((x) => Port.fromJson(x))),
iotDeviceTags: json["iot_device_tags"] == null ? null : List<IotDeviceTag>.from(json["iot_device_tags"].map((x) => IotDeviceTag.fromJson(x))),
entityAddresses: json["entity_addresses"] == null ? null : List<EntityAddress>.from(json["entity_addresses"].map((x) => EntityAddress.fromJson(x))),
availablePorts: json["available_ports"] == null ? null : List<String>.from(json["available_ports"].map((x) => x)),
mobile: json["mobile"] == null ? null : Mobile.fromJson(json["mobile"]),
);
Map<String, dynamic> toJson() => {
"device_id": deviceId == null ? null : deviceId,
"public_id": publicId == null ? null : publicId,
"company_id": companyId == null ? null : companyId,
"company": company == null ? null : company,
"label": label == null ? null : label,
"mobile_provider_id": mobileProviderId == null ? null : mobileProviderId,
"mobile_provider": mobileProvider == null ? null : mobileProvider,
"hologram_device_id": hologramDeviceId == null ? null : hologramDeviceId,
"hologram_link_id": hologramLinkId == null ? null : hologramLinkId,
"firmware_version_id": firmwareVersionId == null ? null : firmwareVersionId,
"version": version == null ? null : version,
"formatted_version": formattedVersion == null ? null : formattedVersion,
"device_type_id": deviceTypeId == null ? null : deviceTypeId,
"device_type": deviceType == null ? null : deviceType,
"ip_address": ipAddress == null ? null : ipAddress,
"record_interval": recordInterval == null ? null : recordInterval,
"upload_interval": uploadInterval == null ? null : uploadInterval,
"power_mode": powerMode == null ? null : powerMode,
"connectivity": connectivity == null ? null : connectivity,
"connectivity_class": connectivityClass == null ? null : connectivityClass,
"users_last_record_date": usersLastRecordDate == null ? null : usersLastRecordDate,
"gmt_last_record_date": gmtLastRecordDate == null ? null : gmtLastRecordDate?.toIso8601String(),
"battery": battery == null ? null : battery,
"battery_percentage": batteryPercentage == null ? null : batteryPercentage,
"battery_class": batteryClass == null ? null : batteryClass,
"battery_icon": batteryIcon == null ? null : batteryIcon,
"signal_quality": signalQuality == null ? null : signalQuality,
"signal_quality_class": signalQualityClass == null ? null : signalQualityClass,
"signal_quality_text": signalQualityText == null ? null : signalQualityText,
"signal_quality_icon": signalQualityIcon == null ? null : signalQualityIcon,
"queued_records": queuedRecords == null ? null : queuedRecords,
"command": command == null ? null : command,
"status": status == null ? null : status,
"status_class": statusClass == null ? null : statusClass,
"purchase_date": purchaseDate == null ? null : "${purchaseDate?.year.toString().padLeft(4, '0')}-${purchaseDate?.month.toString().padLeft(2, '0')}-${purchaseDate?.day.toString().padLeft(2, '0')}",
"warranty_period": warrantyPeriod == null ? null : warrantyPeriod,
"warranty_expires": warrantyExpires == null ? null : "${warrantyExpires?.year.toString().padLeft(4, '0')}-${warrantyExpires?.month.toString().padLeft(2, '0')}-${warrantyExpires?.day.toString().padLeft(2, '0')}",
"warranty_status": warrantyStatus == null ? null : warrantyStatus,
"temperature_class": temperatureClass == null ? null : temperatureClass,
"temperature_metric": temperatureMetric == null ? null : temperatureMetric,
"temperature_imperial": temperatureImperial == null ? null : temperatureImperial,
"surge_protection": surgeProtection == null ? null : surgeProtection,
"total_products": totalProducts == null ? null : totalProducts,
"temperature_low_threshold": temperatureLowThreshold,
"temperature_high_threshold": temperatureHighThreshold,
"notes": notes,
"import_id": importId,
"deleted": deleted == null ? null : deleted,
"created_by": createdBy == null ? null : createdBy,
"last_updated_by": lastUpdatedBy == null ? null : lastUpdatedBy,
"deleted_by": deletedBy,
"date_created": dateCreated,
"date_modified": dateModified == null ? null : dateModified,
"date_deleted": dateDeleted,
"scope": scope == null ? null : scope,
"owner": owner == null ? null : owner,
"links": links == null ? null : links!.toJson(),
"ports": ports == null ? null : List<dynamic>.from(ports!.map((x) => x.toJson())),
"iot_device_tags": iotDeviceTags == null ? null : List<dynamic>.from(iotDeviceTags!.map((x) => x.toJson())),
"entity_addresses": entityAddresses == null ? null : List<dynamic>.from(entityAddresses!.map((x) => x.toJson())),
"available_ports": availablePorts == null ? null : List<dynamic>.from(availablePorts!.map((x) => x)),
"mobile": mobile == null ? null : mobile?.toJson(),
};
}
class EntityAddress {
EntityAddress({
required this.entityAddressesId,
required this.objectRef,
required this.objectId,
required this.address1,
required this.address2,
required this.city,
required this.state,
required this.zipCode,
required this.zipCodeExt,
required this.countryName,
required this.countryIso2,
required this.countryIso3,
required this.countryId,
required this.fullSingleLineAddress,
required this.fullMultiLineAddress,
required this.addressType,
required this.prime,
required this.primeType,
required this.primeClass,
required this.mapsLink,
required this.deleted,
required this.createdBy,
required this.lastUpdatedBy,
required this.deletedBy,
required this.dateCreated,
required this.dateModified,
@required this.dateDeleted,
@required this.links,
});
final String entityAddressesId;
final String objectRef;
final String objectId;
final String address1;
final String address2;
final String city;
final String state;
final String zipCode;
final dynamic zipCodeExt;
final String countryName;
final String countryIso2;
final String countryIso3;
final String countryId;
final String fullSingleLineAddress;
final String fullMultiLineAddress;
final String addressType;
final String prime;
final String primeType;
final String primeClass;
final String mapsLink;
final String deleted;
final String createdBy;
final String lastUpdatedBy;
final dynamic deletedBy;
final String dateCreated;
final String dateModified;
final dynamic dateDeleted;
final EntityAddressLinks? links;
factory EntityAddress.fromJson(Map<String, dynamic> json) => EntityAddress(
entityAddressesId: json["entity_addresses_id"] == null ? null : json["entity_addresses_id"],
objectRef: json["object_ref"] == null ? null : json["object_ref"],
objectId: json["object_id"] == null ? null : json["object_id"],
address1: json["address1"] == null ? null : json["address1"],
address2: json["address2"] == null ? null : json["address2"],
city: json["city"] == null ? null : json["city"],
state: json["state"] == null ? null : json["state"],
zipCode: json["zip_code"] == null ? null : json["zip_code"],
zipCodeExt: json["zip_code_ext"],
countryName: json["country_name"] == null ? null : json["country_name"],
countryIso2: json["country_iso_2"] == null ? null : json["country_iso_2"],
countryIso3: json["country_iso_3"] == null ? null : json["country_iso_3"],
countryId: json["country_id"] == null ? null : json["country_id"],
fullSingleLineAddress: json["full_single_line_address"] == null ? null : json["full_single_line_address"],
fullMultiLineAddress: json["full_multi_line_address"] == null ? null : json["full_multi_line_address"],
addressType: json["address_type"] == null ? null : json["address_type"],
prime: json["prime"] == null ? null : json["prime"],
primeType: json["prime_type"] == null ? null : json["prime_type"],
primeClass: json["prime_class"] == null ? null : json["prime_class"],
mapsLink: json["maps_link"] == null ? null : json["maps_link"],
deleted: json["deleted"] == null ? null : json["deleted"],
createdBy: json["created_by"] == null ? null : json["created_by"],
lastUpdatedBy: json["last_updated_by"] == null ? null : json["last_updated_by"],
deletedBy: json["deleted_by"],
dateCreated: json["date_created"] == null ? null : json["date_created"],
dateModified: json["date_modified"] == null ? null : json["date_modified"],
dateDeleted: json["date_deleted"],
links: json["links"] == null ? null : EntityAddressLinks.fromJson(json["links"]),
);
Map<String, dynamic> toJson() => {
"entity_addresses_id": entityAddressesId == null ? null : entityAddressesId,
"object_ref": objectRef == null ? null : objectRef,
"object_id": objectId == null ? null : objectId,
"address1": address1 == null ? null : address1,
"address2": address2 == null ? null : address2,
"city": city == null ? null : city,
"state": state == null ? null : state,
"zip_code": zipCode == null ? null : zipCode,
"zip_code_ext": zipCodeExt,
"country_name": countryName == null ? null : countryName,
"country_iso_2": countryIso2 == null ? null : countryIso2,
"country_iso_3": countryIso3 == null ? null : countryIso3,
"country_id": countryId == null ? null : countryId,
"full_single_line_address": fullSingleLineAddress == null ? null : fullSingleLineAddress,
"full_multi_line_address": fullMultiLineAddress == null ? null : fullMultiLineAddress,
"address_type": addressType == null ? null : addressType,
"prime": prime == null ? null : prime,
"prime_type": primeType == null ? null : primeType,
"prime_class": primeClass == null ? null : primeClass,
"maps_link": mapsLink == null ? null : mapsLink,
"deleted": deleted == null ? null : deleted,
"created_by": createdBy == null ? null : createdBy,
"last_updated_by": lastUpdatedBy == null ? null : lastUpdatedBy,
"deleted_by": deletedBy,
"date_created": dateCreated == null ? null : dateCreated,
"date_modified": dateModified == null ? null : dateModified,
"date_deleted": dateDeleted,
"links": links == null ? null : links?.toJson(),
};
}
class EntityAddressLinks {
EntityAddressLinks({
required this.self,
});
final String self;
factory EntityAddressLinks.fromJson(Map<String, dynamic> json) => EntityAddressLinks(
self: json["self"] == null ? null : json["self"],
);
Map<String, dynamic> toJson() => {
"self": self == null ? null : self,
};
}
class IotDeviceTag {
IotDeviceTag({
required this.id,
required this.deviceId,
required this.tagId,
required this.tag,
required this.companyId,
required this.createdBy,
required this.lastUpdatedBy,
required this.deletedBy,
required this.dateCreated,
required this.dateModified,
required this.dateDeleted,
required this.scope,
required this.owner,
required this.links,
});
final String id;
final String deviceId;
final String tagId;
final String tag;
final String companyId;
final String createdBy;
final dynamic lastUpdatedBy;
final dynamic deletedBy;
final String dateCreated;
final dynamic dateModified;
final dynamic dateDeleted;
final String scope;
final String owner;
final EntityAddressLinks? links;
factory IotDeviceTag.fromJson(Map<String, dynamic> json) => IotDeviceTag(
id: json["id"] == null ? null : json["id"],
deviceId: json["device_id"] == null ? null : json["device_id"],
tagId: json["tag_id"] == null ? null : json["tag_id"],
tag: json["tag"] == null ? null : json["tag"],
companyId: json["company_id"] == null ? null : json["company_id"],
createdBy: json["created_by"] == null ? null : json["created_by"],
lastUpdatedBy: json["last_updated_by"],
deletedBy: json["deleted_by"],
dateCreated: json["date_created"] == null ? null : json["date_created"],
dateModified: json["date_modified"],
dateDeleted: json["date_deleted"],
scope: json["scope"] == null ? null : json["scope"],
owner: json["owner"] == null ? null : json["owner"],
links: json["links"] == null ? null : EntityAddressLinks.fromJson(json["links"]),
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"device_id": deviceId == null ? null : deviceId,
"tag_id": tagId == null ? null : tagId,
"tag": tag == null ? null : tag,
"company_id": companyId == null ? null : companyId,
"created_by": createdBy == null ? null : createdBy,
"last_updated_by": lastUpdatedBy,
"deleted_by": deletedBy,
"date_created": dateCreated == null ? null : dateCreated,
"date_modified": dateModified,
"date_deleted": dateDeleted,
"scope": scope == null ? null : scope,
"owner": owner == null ? null : owner,
"links": links == null ? null : links?.toJson(),
};
}
class DeviceLinks {
DeviceLinks({
required this.self,
required this.customer,
});
final String self;
final String customer;
factory DeviceLinks.fromJson(Map<String, dynamic> json) => DeviceLinks(
self: json["self"] == null ? null : json["self"],
customer: json["customer"] == null ? null : json["customer"],
);
Map<String, dynamic> toJson() => {
"self": self == null ? null : self,
"customer": customer == null ? null : customer,
};
}
Here is where I am making my api call:
import 'dart:convert';
import 'package:gateway_device/models/device_model.dart';
import 'package:gateway_device/models/devices_list_model.dart';
import 'package:gateway_device/utils/app_constants.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class ApiService {
Future getSingleDevice(int id) async {
final singleDeviceUrl = Uri.parse(AppConstants.BASE_URL
AppConstants.DEVICE_LIST_URI
'/'
id.toString());
print(singleDeviceUrl);
final response = await http.get(singleDeviceUrl, headers: {
'Authorization': 'Bearer ' AppConstants.TOKEN,
'X-API-KEY': AppConstants.API_KEY
});
if (response.statusCode == 200) {
// print(response.body);
// print(json);
var body = json.decode(response.body);
print(body);
return DeviceClass.fromJson(body);
} else {
// print(response.statusCode);
// print(response.body);
print("no data");
}
}
}
The interesting thing to note here is that when I print(body); I am getting something that looks like what I want.
Here is where I am trying to use the data:
import 'package:flutter/material.dart';
import 'package:gateway_device/backend/api/api_services.dart';
import 'package:gateway_device/models/device_model.dart';
import 'dart:convert';
class DeviceProfileWidget extends StatelessWidget {
final int id;
const DeviceProfileWidget({Key? key, required this.id}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: FutureBuilder(
future: ApiService().getSingleDevice(id),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
DeviceClass device = snapshot.data;
print(device);
return Scaffold(
body: Container(
margin: EdgeInsets.only(top: 125,left: 125),
child: Row(
children: [
Text(device.deviceId)
],
),
),
);
}
return const Center(child: CircularProgressIndicator());
}));
}
}
The interesting thing to note here, is that when I try to print(device), I get Instance of DeviceClass. If I try to print(device.deviceId) or any other field that contains data (its evident that they should based on my previous screenshot) I get null.
To clarify, if needed, I am trying to print device and device.deviceId after I assign device to snapshot.data, but before I return my scaffold.
I have been working on this for quite some time and I am stuck, frustrated, and need help.
Thanks in advance.
CodePudding user response:
Your problem is that your classes does not override the toString()
method which are part of the class Object
. The toString()
method are automatically called by print()
and other scenarios where an object are asked to be represented as text. The default implementation of this method is just printing the name of the class which the object created from.
If you just want to use this for debugging, the simplest might just be to call the toJson()
method when calling toString()
on Device
. So something like this:
class Device {
Device({
required this.device,
});
final DeviceClass? device;
factory Device.fromJson(Map<String, dynamic> json) => Device(
device: json["device"] == null ? null : DeviceClass.fromJson(json["device"]),
);
Map<String, dynamic> toJson() => {
"device": device == null ? null : device?.toJson(),
};
// Start: Added method
@override
String toString() => toJson().toString();
// End: Added method
}
But you are free to generate another string in your toString()
method.