I want to retrive each entity from following data in flutter - flutter

I want to sort each entity from following data in flutter
i.e enrollment_no,nationality,mother this data is coming from api
"personal":
"{\"enrollment_no\":\"1701\",
\"nationality\":\"INDIAN\",
\"driver_mobile\":\"-\",
\"mother\":\"JAGRUTIBAHEN SHRIKANT SONI\",
\"email\":\"SHRIKANT206#YAHOO.CO.IN\",
\"student_photo\":\"/container/school_data/BRS/photo/Student/1701.jpg\",
\"name\":\"NEYSA SHRIKANT SONI\",
\"mother_mobile\":\"+971507603564\",
\"father_mobile\":\"+971503171294\",
\"father\":\"SHRIKANT INDUKANT SONI\"}",
//I trying following code to sort data but can't achieve
if(personal == data['personal']) {
for (int i = 0; i < data['personal'].length; i++)
{
arrayp = personal;
print(arrayp);
var array1=arrayp[0]['father'];
print(array1);
}
}

1. Your JSON from API
{
"personal":
{
"enrollment_no": "1701",
"nationality": "INDIAN",
"driver_mobile": "-",
"mother": "JAGRUTIBAHEN SHRIKANT SONI",
"email": "SHRIKANT206#YAHOO.CO.IN",
"student_photo": "/container/school_data/BRS/photo/Student/1701.jpg",
"name": "NEYSA SHRIKANT SONI",
"mother_mobile": "+971507603564",
"father_mobile": "+971503171294",
"father": "SHRIKANT INDUKANT SONI"
}
}
2. Go To https://javiercbk.github.io/json_to_dart/
Convert your Json to Dart Classes.
class Personal {
PersonalData personal;
Personal({this.personal});
factory Personal.fromJson(Map<String, dynamic> json) {
return Personal(
personal: json['personal'] != null ?
PersonalData.fromJson(json['personal']) : null,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.personal != null) {
data['personal'] = this.personal.toJson();
}
return data;
}
}
class PersonalData {
String driver_mobile;
String email;
String enrollment_no;
String father;
String father_mobile;
String mother;
String mother_mobile;
String name;
String nationality;
String student_photo;
PersonalData({this.driver_mobile, this.email, this.enrollment_no, this.father, this.father_mobile, this.mother, this.mother_mobile, this.name, this.nationality, this.student_photo});
factory PersonalData.fromJson(Map<String, dynamic> json) {
return PersonalData(
driver_mobile: json['driver_mobile'],
email: json['email'],
enrollment_no: json['enrollment_no'],
father: json['father'],
father_mobile: json['father_mobile'],
mother: json['mother'],
mother_mobile: json['mother_mobile'],
name: json['name'],
nationality: json['nationality'],
student_photo: json['student_photo'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['driver_mobile'] = this.driver_mobile;
data['email'] = this.email;
data['enrollment_no'] = this.enrollment_no;
data['father'] = this.father;
data['father_mobile'] = this.father_mobile;
data['mother'] = this.mother;
data['mother_mobile'] = this.mother_mobile;
data['name'] = this.name;
data['nationality'] = this.nationality;
data['student_photo'] = this.student_photo;
return data;
}
}
3. Now time for you api response
_getResponseFromApi() asyn{
var response = await http.post({your parameters})
var data = Personal.fromJson(json.decode(response.body));
var listOfPersonData = data.personal
}

Related

How to save this nested class in Isar DB Flutter

I have the following 4 classes. In this, only the ProductGroup is saved, ProductVariant, ProductSize and ProductColor are not stored. Please help me with this.
product_group.dart
#Collection()
class ProductGroup {
late Id id;
#Index(caseSensitive: false)
late String productGroupName;
final productVariants = IsarLinks<ProductVariant>();
ProductGroup();
ProductGroup.fromJson(Map<String, dynamic> json) {
id = json['Id'];
productGroupName = json['PG'];
if (json['Ps'] != null) {
json['Ps'].forEach((variant) {
productVariants.add(ProductVariant.fromJson(variant));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['PG'] = productGroupName;
data['Ps'] = productVariants.map((variant) => variant.toJson()).toList();
return data;
}
}
product_variant.dart
#Collection()
class ProductVariant {
late Id id;
late String variantName;
final productSizes = IsarLinks<ProductSize>();
ProductVariant();
ProductVariant.fromJson(Map<String, dynamic> json) {
id = json['Id'];
variantName = json['St'];
if (json['Ss'] != null) {
json['Ss'].forEach((v) {
productSizes.add(ProductSize.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['St'] = variantName;
data['Ss'] = productSizes.map((v) => v.toJson()).toList();
return data;
}
}
product_size.dart
#Collection()
class ProductSize {
late Id id;
late String size;
final productColors = IsarLinks<ProductColor>();
ProductSize();
ProductSize.fromJson(Map<String, dynamic> json) {
id = json['Id'];
size = json['S'];
if (json['Cs'] != null) {
json['Cs'].forEach((v) {
productColors.add(ProductColor.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['S'] = size;
data['Cs'] = productColors.map((color) => color.toJson()).toList();
return data;
}
}
product_color.dart
#Collection()
class ProductColor {
late Id id;
late String colorName;
late String colorHexCode;
ProductColor();
ProductColor.fromJson(Map<String, dynamic> json) {
id = json['Id'];
colorName = json['C'];
colorHexCode = json['CC'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['Id'] = id;
data['C'] = colorName;
data['CC'] = colorHexCode;
return data;
}
}
I am parsing the json and saving it in Isar
convertJsonToIsar() async {
try {
// For testing purposes, loading Json from assets, in Prod, Json will be fetched from server
final String response = await rootBundle.loadString('assets/pr_dump.json');
final data = await json.decode(response);
List<ProductGroup> productGroupList = [];
data.forEach((item) {
productGroupList.add(ProductGroup.fromJson(item));
});
Isar _isar = getIsar();
_isar.writeTxnSync(() {
_isar.productGroups.putAllSync(productGroupList, saveLinks: true);
});
} catch (e) {
// Handle Error
print('Caught Error');
print(e.toString());
return 0;
}
}
Only the ProductGroup is stored, ProductVariant, ProductSize and ProductColor are not stored. Please help me with this.

Pulling data from API masked with UUID string as a key with dart

When I try try to pull my Add_ons. it is prepared with data key of a UUID and values of List body. Essentially what I am asking is how I get the values (name, price and type) in add_ons. Structure at the end.
Here is the preparation of the data to be sent to API
Map<String, dynamic> extrasJsonPrepare() {
Map<String, dynamic> addOnBody = {};
if (extras.isNotEmpty) {
for (int i = 0; i < extras.length; i++) {
addOnBody["${uuid.v4()}"] = {
"name": "${extras[i].name}",
"price": extras[i].price,
"type": "extras"
};
}
}
...........
}
Trying to pull the data from the API code
import 'dart:convert';
import 'package:uuid/uuid.dart';
MealJSON mealFromJson(String str) => MealJSON.fromJson(json.decode(str));
String mealToJson(MealJSON data) => json.encode(data.toJson());
class MealJSON {
int code;
List<MealboxListing> data;
MealJSON({this.code, this.data});
MealJSON.fromJson(Map<String, dynamic> json) {
code = json['code'];
data = json['data'] != null
? (json['data'] as Iterable)
.map((data) => MealboxListing.fromJson(data))
.toList()
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['code'] = this.code;
if (this.data != null) {
data['data'] = this.data;
}
return data;
}
}
class MealboxListing {
List<AddOn> addOns;
bool availability;
double averageRating;
String cityLive;
String deliveryDate;
String description;
List<String> imageDetails;
String kitchenDetails;
String listingId;
int numberOfMeals;
String origin;
String title;
double price;
List<String> preferences;
List<String> tag;
List<String> included;
MealboxListing(
{this.addOns,
this.availability,
this.averageRating,
this.cityLive,
this.deliveryDate,
this.description,
this.imageDetails,
this.kitchenDetails,
this.listingId,
this.numberOfMeals,
this.origin,
this.title,
this.preferences,
this.tag,
this.included,
this.price});
MealboxListing.fromJson(Map<String, dynamic> json) {
// addOns = json['add_ons'] != null ? new AddOn.fromJson(json[addOns]) : null;
if (json['add_ons'] != null) {
addOns = new List<AddOn>();
json['add_ons'].forEach((v) {
addOns.add(new AddOn.fromJson(v));
});
}
availability = json['available'];
averageRating = json['average_rating'];
cityLive = json['city_live'];
deliveryDate = json['delivery_on'];
description = json['description'];
imageDetails = json['img_url'].cast<String>();
kitchenDetails = json['kitchen'];
listingId = json['listing_id'];
numberOfMeals = json['no_of_meals'];
origin = json['origin'];
title = json['title'];
price = json['price_before_sankara_charges'];
preferences = json['preferences'].cast<String>();
tag = json['tags'].cast<String>();
included = json['whats_included'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.addOns != null) {
data['add_ons'] = this.addOns.map((v) => v.toJson()).toList();
}
data['available'] = this.availability;
data['average_rating'] = this.averageRating;
data['city_live'] = this.cityLive;
data['delivery_on'] = this.deliveryDate;
data['description'] = this.description;
data['img_url'] = this.imageDetails;
data['kitchen'] = this.kitchenDetails;
data['listing_id'] = this.listingId;
data['no_of_meals'] = this.numberOfMeals;
data['origin'] = this.origin;
data['title'] = this.title;
data['preferences'] = this.preferences;
data['tags'] = this.tag;
data['whats_included'] = this.included;
data['price_before_sankara_charges'] = this.price;
return data;
}
}
class AddOn {
String name;
String type;
int price;
// List<uuid> = Uuid();
// var uuid = Uuid();
AddOn({
// this.uuid,
this.name,
this.price,
this.type,
});
AddOn.fromJson(Map<String, dynamic> json) {
// uuid = json['$uuid'];
name = json['name'];
price = json['price'];
type = json['type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
// data['$uuid'] = this.uuid;
data['name'] = this.name;
data['price'] = this.price;
data['type'] = this.type;
return data;
}
}
Structure of API
{
"add_ons": {
"681c3755-40a1-4711-9072-c848a2eaeea3": {
"name": "hgfhfgh",
"price": 9,
"type": "drinks"
},
"90e2bfe7-f81b-47c1-bb02-0fb227ddfff2": {
"name": "gdfgfdg",
"price": 9,
"type": "extras"
},
"b5c78d1c-9ce3-46ce-a168-6358259d4982": {
"name": "ghgfhgfh",
"price": 9,
"type": "sides"
}
},
"available": true,
"average_rating": 0.0,
"city_live": "Fredericton",
"delivery_on": "Tuesday",
"description": "dsadasds",
"img_url": [],
"kitchen": "sadasda",
"listing_id": "cd78ac9f-0f9c-49eb-8a52-970c2017fee9",
"no_of_meals": 1,
"origin": "Canada",
"preferences": [
"Gluten Free"
],
"price_before_sankara_charges": 6.0,
"tags": [],
"title": "dsadsad",
"whats_included": []
},
Fixed by adding these lines of code
var innerMap = json['add_ons'];
var targetMap = Map<String, AddOn>();
innerMap.forEach((key, value) {
targetMap.addAll({key: AddOn.fromJson(value)});
});

Receive data from API using Flutter

I work with flutter not so long and i don't know how to retrieve data as same as I described below.
I create an app with API. I received all data except Gallery images, program, additionalInfo.
Can anyone explain to me how I can retrieve gallery images, program and additionalInfo from API?
If you can write code snippets which I can use. Thanks.
'https://tripvenue.ru/api/v1/experiences/448'
import 'dart:convert';
ExperiencesByCityId experiencesByCityIdFromJson(String str) =>
ExperiencesByCityId.fromJson(json.decode(str));
String experiencesByCityIdToJson(ExperiencesByCityId data) =>
json.encode(data.toJson());
class ExperiencesByCityId {
ExperiencesByCityId({
this.id,
this.title,
this.promoText,
this.country,
this.city,
this.mainPhoto,
this.type,
this.languages,
this.instantBooking,
this.duration,
this.votesCount,
this.votesAvg,
this.url,
this.pricing,
this.teaserText,
this.description,
this.program,
this.additionalInfo,
this.gallery,
this.guestsMin,
this.guestsMax,
});
int id;
String title;
String promoText;
City country;
City city;
MainPhoto mainPhoto;
String type;
List<String> languages;
bool instantBooking;
int duration;
int votesCount;
double votesAvg;
String url;
Pricing pricing;
String teaserText;
String description;
List<Program> program;
List<String> additionalInfo;
List<Gallery> gallery;
int guestsMin;
int guestsMax;
factory ExperiencesByCityId.fromJson(Map<String, dynamic> json) =>
ExperiencesByCityId(
id: json["id"],
title: json["title"],
promoText: json["promo_text"],
country: City.fromJson(json["country"]),
city: City.fromJson(json["city"]),
mainPhoto: MainPhoto.fromJson(json["main_photo"]),
type: json["type"],
languages: List<String>.from(json["languages"].map((x) => x)),
instantBooking: json["instant_booking"],
duration: json["duration"],
votesCount: json["votes_count"],
votesAvg: json["votes_avg"],
url: json["url"],
pricing: Pricing.fromJson(json["pricing"]),
teaserText: json["teaser_text"],
description: json["description"],
program:
List<Program>.from(json["program"].map((x) => Program.fromJson(x))),
additionalInfo:
List<String>.from(json["additional_info"].map((x) => x)),
gallery:
List<Gallery>.from(json["gallery"].map((x) => Gallery.fromJson(x))),
guestsMin: json["guests_min"],
guestsMax: json["guests_max"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"promo_text": promoText,
"country": country.toJson(),
"city": city.toJson(),
"main_photo": mainPhoto.toJson(),
"type": type,
"languages": List<dynamic>.from(languages.map((x) => x)),
"instant_booking": instantBooking,
"duration": duration,
"votes_count": votesCount,
"votes_avg": votesAvg,
"url": url,
"pricing": pricing.toJson(),
"teaser_text": teaserText,
"description": description,
"program": List<dynamic>.from(program.map((x) => x.toJson())),
"additional_info": List<dynamic>.from(additionalInfo.map((x) => x)),
"gallery": List<dynamic>.from(gallery.map((x) => x.toJson())),
"guests_min": guestsMin,
"guests_max": guestsMax,
};
}
class City {
City({
this.id,
this.name,
});
int id;
String name;
factory City.fromJson(Map<String, dynamic> json) => City(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
class Gallery {
Gallery({
this.fid,
this.uri,
this.url,
});
int fid;
String uri;
String url;
factory Gallery.fromJson(Map<String, dynamic> json) => Gallery(
fid: json["fid"],
uri: json["uri"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"fid": fid,
"uri": uri,
"url": url,
};
}
class MainPhoto {
MainPhoto({
this.id,
this.uri,
this.url,
});
int id;
String uri;
String url;
factory MainPhoto.fromJson(Map<String, dynamic> json) => MainPhoto(
id: json["id"],
uri: json["uri"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"id": id,
"uri": uri,
"url": url,
};
}
class Pricing {
Pricing({
this.type,
this.amount,
this.currency,
this.formatted,
this.groupSizeMin,
this.groupSizeMax,
});
String type;
double amount;
String currency;
String formatted;
int groupSizeMin;
int groupSizeMax;
factory Pricing.fromJson(Map<String, dynamic> json) => Pricing(
type: json["type"],
amount: json["amount"],
currency: json["currency"],
formatted: json["formatted"],
groupSizeMin: json["group_size_min"],
groupSizeMax: json["group_size_max"],
);
Map<String, dynamic> toJson() => {
"type": type,
"amount": amount,
"currency": currency,
"formatted": formatted,
"group_size_min": groupSizeMin,
"group_size_max": groupSizeMax,
};
}
class Program {
Program({
this.first,
this.second,
});
String first;
Second second;
factory Program.fromJson(Map<String, dynamic> json) => Program(
first: json["first"],
second: secondValues.map[json["second"]],
);
Map<String, dynamic> toJson() => {
"first": first,
"second": secondValues.reverse[second],
};
}
enum Second { EMPTY, SECOND, PURPLE }
final secondValues = EnumValues({
"": Second.EMPTY,
"по возможности посмотрим их на закате": Second.PURPLE,
"здесь вы сделаете классные фото на заброшке": Second.SECOND
});
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;
}
}
You can generate your Response class from https://jsontodart.com
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Center(
child: TextButton(
onPressed: () async {
var response = await http.get(
Uri.parse('https://tripvenue.ru/api/v1/experiences/448'));
var body = response.body;
Response myResponse = Response.fromJson(json.decode(body));
print(myResponse.gallery.first.url);
},
child: Text(
"press",
),
),
)));
}
}
class Response {
int id;
String title;
String promoText;
Country country;
Country city;
MainPhoto mainPhoto;
String type;
List<String> languages;
bool instantBooking;
int duration;
int votesCount;
double votesAvg;
String url;
Pricing pricing;
String teaserText;
String description;
List<Program> program;
List<String> additionalInfo;
List<Gallery> gallery;
int guestsMin;
int guestsMax;
Response(
{this.id,
this.title,
this.promoText,
this.country,
this.city,
this.mainPhoto,
this.type,
this.languages,
this.instantBooking,
this.duration,
this.votesCount,
this.votesAvg,
this.url,
this.pricing,
this.teaserText,
this.description,
this.program,
this.additionalInfo,
this.gallery,
this.guestsMin,
this.guestsMax});
Response.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
promoText = json['promo_text'];
country =
json['country'] != null ? new Country.fromJson(json['country']) : null;
city = json['city'] != null ? new Country.fromJson(json['city']) : null;
mainPhoto = json['main_photo'] != null
? new MainPhoto.fromJson(json['main_photo'])
: null;
type = json['type'];
languages = json['languages'].cast<String>();
instantBooking = json['instant_booking'];
duration = json['duration'];
votesCount = json['votes_count'];
votesAvg = json['votes_avg'];
url = json['url'];
pricing =
json['pricing'] != null ? new Pricing.fromJson(json['pricing']) : null;
teaserText = json['teaser_text'];
description = json['description'];
if (json['program'] != null) {
program = <Program>[];
json['program'].forEach((v) {
program.add(new Program.fromJson(v));
});
}
additionalInfo = json['additional_info'].cast<String>();
if (json['gallery'] != null) {
gallery = <Gallery>[];
json['gallery'].forEach((v) {
gallery.add(new Gallery.fromJson(v));
});
}
guestsMin = json['guests_min'];
guestsMax = json['guests_max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['promo_text'] = this.promoText;
if (this.country != null) {
data['country'] = this.country.toJson();
}
if (this.city != null) {
data['city'] = this.city.toJson();
}
if (this.mainPhoto != null) {
data['main_photo'] = this.mainPhoto.toJson();
}
data['type'] = this.type;
data['languages'] = this.languages;
data['instant_booking'] = this.instantBooking;
data['duration'] = this.duration;
data['votes_count'] = this.votesCount;
data['votes_avg'] = this.votesAvg;
data['url'] = this.url;
if (this.pricing != null) {
data['pricing'] = this.pricing.toJson();
}
data['teaser_text'] = this.teaserText;
data['description'] = this.description;
if (this.program != null) {
data['program'] = this.program.map((v) => v.toJson()).toList();
}
data['additional_info'] = this.additionalInfo;
if (this.gallery != null) {
data['gallery'] = this.gallery.map((v) => v.toJson()).toList();
}
data['guests_min'] = this.guestsMin;
data['guests_max'] = this.guestsMax;
return data;
}
}
class Country {
int id;
String name;
Country({this.id, this.name});
Country.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;
}
}
class MainPhoto {
int id;
String uri;
String url;
MainPhoto({this.id, this.uri, this.url});
MainPhoto.fromJson(Map<String, dynamic> json) {
id = json['id'];
uri = json['uri'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['uri'] = this.uri;
data['url'] = this.url;
return data;
}
}
class Pricing {
String type;
double amount;
String currency;
String formatted;
int groupSizeMin;
int groupSizeMax;
Pricing(
{this.type,
this.amount,
this.currency,
this.formatted,
this.groupSizeMin,
this.groupSizeMax});
Pricing.fromJson(Map<String, dynamic> json) {
type = json['type'];
amount = json['amount'];
currency = json['currency'];
formatted = json['formatted'];
groupSizeMin = json['group_size_min'];
groupSizeMax = json['group_size_max'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['type'] = this.type;
data['amount'] = this.amount;
data['currency'] = this.currency;
data['formatted'] = this.formatted;
data['group_size_min'] = this.groupSizeMin;
data['group_size_max'] = this.groupSizeMax;
return data;
}
}
class Program {
String first;
String second;
Program({this.first, this.second});
Program.fromJson(Map<String, dynamic> json) {
first = json['first'];
second = json['second'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['first'] = this.first;
data['second'] = this.second;
return data;
}
}
class Gallery {
int fid;
String uri;
String url;
Gallery({this.fid, this.uri, this.url});
Gallery.fromJson(Map<String, dynamic> json) {
fid = json['fid'];
uri = json['uri'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['fid'] = this.fid;
data['uri'] = this.uri;
data['url'] = this.url;
return data;
}
}

How to register multiple adapters with hive for single modal class

I am kind of new to flutter and working on the application where I need to save data locally to use it later when user will be offline.
I have a modal class with multiple inner classes:
Modal Class:
import 'package:hive/hive.dart';
part 'DownloadResponse.g.dart';
#HiveType(typeId: 1)
class DownloadResponse extends HiveObject {
#HiveField(0)
UserInfo userInfo;
#HiveField(1)
AppSetting appSetting;
#HiveField(2)
List<Seals> seals;
#HiveField(3)
String success;
#HiveField(4)
String message;
DownloadResponse(
{this.userInfo, this.appSetting, this.seals, this.success, this.message});
DownloadResponse.fromJson(Map<String, dynamic> json) {
userInfo = json['userInfo'] != null
? new UserInfo.fromJson(json['userInfo'])
: null;
appSetting = json['appSetting'] != null
? new AppSetting.fromJson(json['appSetting'])
: null;
if (json['seals'] != null) {
seals = new List<Seals>();
json['seals'].forEach((v) {
seals.add(new Seals.fromJson(v));
});
}
success = json['success'];
message = json['message'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.userInfo != null) {
data['userInfo'] = this.userInfo.toJson();
}
if (this.appSetting != null) {
data['appSetting'] = this.appSetting.toJson();
}
if (this.seals != null) {
data['seals'] = this.seals.map((v) => v.toJson()).toList();
}
data['success'] = this.success;
data['message'] = this.message;
return data;
}
}
#HiveType(typeId: 2)
class UserInfo extends HiveObject {
String fullName;
String mobileLastSyncDate;
UserInfo({this.fullName, this.mobileLastSyncDate});
UserInfo.fromJson(Map<String, dynamic> json) {
fullName = json['full_name'];
mobileLastSyncDate = json['mobile_last_sync_date'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['full_name'] = this.fullName;
data['mobile_last_sync_date'] = this.mobileLastSyncDate;
return data;
}
}
#HiveType(typeId: 3)
class AppSetting extends HiveObject {
String appWebviewHeight;
String appScreenHeaderSealScan;
String appScreenHeaderSealInfo;
String appScreenHeaderPicture1;
String appScreenHeaderPicture2;
AppSetting(
{this.appWebviewHeight,
this.appScreenHeaderSealScan,
this.appScreenHeaderSealInfo,
this.appScreenHeaderPicture1,
this.appScreenHeaderPicture2});
AppSetting.fromJson(Map<String, dynamic> json) {
appWebviewHeight = json['app_webview_height'];
appScreenHeaderSealScan = json['app_screen_header_seal_scan'];
appScreenHeaderSealInfo = json['app_screen_header_seal_info'];
appScreenHeaderPicture1 = json['app_screen_header_picture_1'];
appScreenHeaderPicture2 = json['app_screen_header_picture_2'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['app_webview_height'] = this.appWebviewHeight;
data['app_screen_header_seal_scan'] = this.appScreenHeaderSealScan;
data['app_screen_header_seal_info'] = this.appScreenHeaderSealInfo;
data['app_screen_header_picture_1'] = this.appScreenHeaderPicture1;
data['app_screen_header_picture_2'] = this.appScreenHeaderPicture2;
return data;
}
}
#HiveType(typeId: 4)
class Seals extends HiveObject {
String sealId;
String sealHtml;
List<Documents> documents;
Seals({this.sealId, this.sealHtml, this.documents});
Seals.fromJson(Map<String, dynamic> json) {
sealId = json['seal_id'];
sealHtml = json['seal_html'];
if (json['documents'] != null) {
documents = new List<Documents>();
json['documents'].forEach((v) {
documents.add(new Documents.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['seal_id'] = this.sealId;
data['seal_html'] = this.sealHtml;
if (this.documents != null) {
data['documents'] = this.documents.map((v) => v.toJson()).toList();
}
return data;
}
}
#HiveType(typeId: 5)
class Documents extends HiveObject {
String documentId;
String documentName;
String documentLink;
Documents({this.documentId, this.documentName, this.documentLink});
Documents.fromJson(Map<String, dynamic> json) {
documentId = json['document_id'];
documentName = json['document_name'];
documentLink = json['document_link'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['document_id'] = this.documentId;
data['document_name'] = this.documentName;
data['document_link'] = this.documentLink;
return data;
}
}
And this is my logic where I am trying to save data in the hive:
// We get the current app directory
WidgetsFlutterBinding.ensureInitialized();
final appDocDir = await getApplicationDocumentsDirectory();
// We initialize Hive and we give him the current path
Hive
..init(appDocDir.path)
..registerAdapter(DownloadResponseAdapter());
var box = await Hive.openBox('driverData');
//box.put('ew32', DownloadResponse('BMW','test', 2002));
UserInfo userInfo = downloadResponse.userInfo;
AppSetting appSetting = downloadResponse.appSetting;
List<Seals> sealList = downloadResponse.seals;
String success = downloadResponse.success;
String message = downloadResponse.message;
await box.put('driverData', DownloadResponse()
..userInfo = userInfo
..appSetting = appSetting
..seals = sealList
..success = success
..message = message);
print(box.get('driverData'));
I get this exception when box.put() runs:
Unhandled Exception: HiveError: Cannot write, unknown type: UserInfo. Did you forget to register an adapter
My question is how do I create and add multiple adapters with hive as my modal class has multiple classes?
I got the answer of the same. You will have all the adapters available in the automated generated file.
You just need to add them before saving data like this:
Hive
..init(appDocDir.path)
..registerAdapter(DownloadResponseAdapter())
..registerAdapter(UserInfoAdapter())
..registerAdapter(AppSettingAdapter())
..registerAdapter(SealsAdapter())
..registerAdapter(DocumentsAdapter()
);

Decode json flutter

I have this data format
message": [
{
"id": 15989,
"title": "xxx",
"body": "xxx",
"type": "abc",
"data_hash": "{\"id\":\"3098\",\"number\":1}",
}, .....]
If I write like this
print(message['data']['type']);
I can get abc, but if I write print(message['data']['data_hash']);, I get invalid arguments error. Why?
I want to get the number in data_hash.
This is the full code
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("===== onMessage ====");
try {
print(message['data']['data_hash']);
} catch (e) {
print(e.toString());
}
});
data_hash row is a json. So you need to decode that row for use.
final data_hash_map = jsonDecode(message['data']['data_hash']);
print(data_hash_map); // { "id": 3098, "number": 1 }
print(data_hash_map["number"]); // for number
Decode your json as below
Map<String, dynamic> jsonData = jsonDecode(message)
I recommend to create a class to predefine the object as followed:
class Message {
int id;
String title;
String body;
String type;
DataHash dataHash;
message({this.id, this.title, this.body, this.type, this.dataHash});
Message.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
body = json['body'];
type = json['type'];
dataHash = json['data_hash'] != null
? new DataHash.fromJson(json['data_hash'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['body'] = this.body;
data['type'] = this.type;
if (this.dataHash != null) {
data['data_hash'] = this.dataHash.toJson();
}
return data;
}
}
class DataHash {
String id;
String number;
DataHash({this.id, this.number});
DataHash.fromJson(Map<String, dynamic> json) {
id = json['id'];
number = json['number'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['number'] = this.number;
return data;
}
}
You can call Message.fromJson(data) to decode.
Messsage message = Message.fromJson(data);
print(message.dataHash.number);
I hope this will work correctly
class _HomeState extends State<Mytimeoff> {
List<Map> list = [];
Map leaveRoot ={};
void getList() async {
var data = await http
.get('https:your api link');
leaveRoot = Map.from(json.decode(data.body));
setState(() {
for (Map js in leaveRoot['leavetype']) {
list.add(js);
}
});
print(jsonData);
}
#override
void initState() {
super.initState();
getList();
}
#override
Widget build(BuildContext context) {
return Scaffold();
}
}