How to access JSON via field? - flutter

I have a JSON
jsonData
{
"data": {
"splashPage": {
"title": "Splash"
},
"homePage": {
"title": "Home"
}
}
}
List<String> accessField = ['data','splashPage'];
final out = accessField.map((e) => "['$e']").join();
Map jsonMapData = jsonDecode(jsonData);
Map<String, dynamic> splashPageJson = '${jsonMapData}$out' as Map<String, dynamic>;
print(splashPageJson);
I got an error can't access to splashPage.
_CastError (type 'String' is not a subtype of type 'Map<String, dynamic>' in type cast)
How can I access to splashPage from JSON?
Note: accessField is dynamic value
If I want to access splashPage, declaration
accessField = ['data','splashPage'];
If I want to access homePage, declaration
accessField = ['data','homePage'];

Is this what you want?
var jsonData = {
"data": {
"splashPage": {
"title": "Splash"
},
"homePage": {
"title": "Home"
}
}
}
Map jsonMapData = jsonDecode(jsonData);
List<String> accessField = ['data','splashPage'];
Map<String, dynamic> requiredResult = jsonMapData[accessField[0]][accessField[1]];

Here's the solution:
First import:
import 'dart:convert';
To store JSON into the map:
final Map<String, dynamic> map = json.decode('{"data":{"splashPage":{"title":"Splash"},"homePage":{"title":"Home"}}}');
To print your requirement:
print(map["data"]["splashPage"]["title"]);

Code for your Model:
class Model {
Model({
this.data,
});
Model.fromJson(Map<String, dynamic> json) {
data = json["data"] != null ? Data.fromJson(json["data"]) : null;
}
Data? data;
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = <String, dynamic>{};
if (data != null) {
map["data"] = data?.toJson();
}
return map;
}
}
class Data {
Data({
this.splashPage,
this.homePage,
});
Data.fromJson(Map<String, dynamic> json) {
splashPage = json["splashPage"] != null
? SplashPage.fromJson(json["splashPage"])
: null;
homePage =
json["homePage"] != null ? HomePage.fromJson(json["homePage"]) : null;
}
SplashPage? splashPage;
HomePage? homePage;
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = <String, dynamic>{};
if (splashPage != null) {
map["splashPage"] = splashPage?.toJson();
}
if (homePage != null) {
map["homePage"] = homePage?.toJson();
}
return map;
}
}
class HomePage {
HomePage({
this.title,
});
HomePage.fromJson(Map<String, dynamic> json) {
title = json["title"];
}
String? title;
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = <String, dynamic>{};
map["title"] = title;
return map;
}
}
class SplashPage {
SplashPage({
this.title,
});
SplashPage.fromJson(Map<String, dynamic> json) {
title = json["title"];
}
String? title;
Map<String, dynamic> toJson() {
final Map<String, dynamic> map = <String, dynamic>{};
map["title"] = title;
return map;
}
}
Code for your usage:
final Model model = Model.fromJson(
json.decode(
'{"data":{"splashPage":{"title":"Splash"},"homePage":{"title":"Home"}}}',
),
);
print(model.data?.splashPage?.title ?? "");
print(model.data?.homePage?.title ?? "");
Don't forgot to import:
import 'dart:convert';

This is a question about conversion of Json data format to native data model. If you publish the Json data earlier, the problem may not be so complicated
try this.
void test() {
var json =
'{"data":{"splashPage":{"title":"Splash"},"homePage":{"title":"Home"}}}';
var map = jsonDecode(json) as Map<String, dynamic>;
var model = DataResponseModel.fromJson(map);
pr(model.data?.homePage?.title); // Home
pr(model.data?.splashPage?.title); // Splash
}
class TitleModel {
String? title;
TitleModel({required this.title});
factory TitleModel.fromJson(Map<String, dynamic> map) =>
TitleModel(title: map['title']);
}
class DataModel {
TitleModel? splashPage;
TitleModel? homePage;
DataModel({required this.splashPage, this.homePage});
factory DataModel.fromJson(Map<String, dynamic> map) => DataModel(
splashPage: TitleModel.fromJson(map['splashPage']),
homePage: TitleModel.fromJson(map['homePage']),
);
}
class DataResponseModel {
DataModel? data;
DataResponseModel({required this.data});
factory DataResponseModel.fromJson(Map<String, dynamic> map) =>
DataResponseModel(
data: DataModel.fromJson(map['data']),
);
}

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.

I am trying to get data from API but having error

This is my model class and I am trying to get all the data but getting error and don't know why.
HomePageModel homePageModelFromJson(String str) => HomePageModel.fromJson(json.decode(str));
String homePageModelToJson(HomePageModel data) => json.encode(data.toJson());
class HomePageModel with ChangeNotifier {
HomePageModel({
this.data,
});
List<Datum>? data;
factory HomePageModel.fromJson(Map<String, dynamic> json) => HomePageModel(
data: List<Datum>.from(json["data"]!.map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data!.map((x) => x.toJson())),
};
}
class Datum {
Datum({
this.schoolid,
this.name,
this.logo,
this.address,
this.contact,
this.principalname,
this.principalcontact,
this.slogan,
this.webAddress,
this.description,
this.email,
this.pan,
this.establishedYear,
});
String? schoolid;
String? name;
String? logo;
String? address;
String? contact;
String? principalname;
String? principalcontact;
String? slogan;
String? webAddress;
String? description;
String? email;
String? pan;
int? establishedYear;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
schoolid: json["schoolid"],
name: json["name"],
logo: json["logo"],
address: json["address"],
contact: json["contact"],
principalname: json["principalname"],
principalcontact: json["principalcontact"],
slogan: json["slogan"],
webAddress: json["web_address"] == null ? null : json["web_address"],
description: json["description"] == null ? null : json["description"],
email: json["email"],
pan: json["pan"],
establishedYear: json["established_year"],
);
Map<String, dynamic> toJson() => {
"schoolid": schoolid,
"name": name,
"logo": logo,
"address": address,
"contact": contact,
"principalname": principalname,
"principalcontact": principalcontact,
"slogan": slogan,
"web_address": webAddress == null ? null : webAddress,
"description": description == null ? null : description,
"email": email,
"pan": pan,
"established_year": establishedYear,
};
}
This is how I am trying to fetch data:
class HomePageModels with ChangeNotifier{
List<HomePageModel> _hItem = [];
List<HomePageModel> get hItem{
return [..._hItem];
}
Future<void> getHomeData(BuildContext context) async{
const url = "https://shikshyasoftware.com.np/CoreApplicationandAPIService-4617993073/api/school";
try{
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
List<HomePageModel> loadedHomeData = [];
if(extractedData == null){
return;
}
if(response.statusCode == 200){
print(extractedData);
}
extractedData.forEach((element){
loadedHomeData.add(HomePageModel.fromJson(element));
});
_hItem = loadedHomeData;
// EasyLoading.showSuccess("data fetched sucessfull");
notifyListeners();
}catch(e){
rethrow;
}
}
}
But I am getting error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
The problem is the way you are trying to parse the data, you don't need to loop over every element to parse it, in your model just make it return a list type like this,
class HomePageModel with ChangeNotifier {
List<Datum>? data;
HomePageModel({this.data});
HomePageModel.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = <Datum>[];
json['data'].forEach((v) {
data!.add(new Datum.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Datum {
Datum({
this.schoolid,
this.name,
this.logo,
this.address,
this.contact,
this.principalname,
this.principalcontact,
this.slogan,
this.webAddress,
this.description,
this.email,
this.pan,
this.establishedYear,
});
String? schoolid;
String? name;
String? logo;
String? address;
String? contact;
String? principalname;
String? principalcontact;
String? slogan;
String? webAddress;
String? description;
String? email;
String? pan;
int? establishedYear;
Datum.fromJson(Map<String, dynamic> json) {
schoolid = json["schoolid"];
name = json["name"];
logo = json["logo"];
address = json["address"];
contact = json["contact"];
principalname = json["principalname"];
principalcontact = json["principalcontact"];
slogan = json["slogan"];
webAddress = json["web_address"];
description = json["description"];
email = json["email"];
pan = json["pan"];
establishedYear = json["established_year"];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['schoolid'] = this.schoolid;
data['name'] = this.name;
data['logo'] = this.logo;
data['address'] = this.address;
data['contact'] = this.contact;
data['principalname'] = this.principalname;
data['principalcontact'] = this.principalcontact;
data['slogan'] = this.slogan;
data['web_address'] = this.webAddress;
data['description'] = this.description;
data['email'] = this.email;
data['pan'] = this.pan;
data['established_year'] = this.establishedYear;
return data;
}
}
and in your view model you can just parse the extracted data from response.body like this,
class HomePageModels with ChangeNotifier {
HomePageModel? _hItem;
HomePageModel get hItem {
return _hItem!;
}
Future<void> getHomeData(BuildContext context) async {
const url =
"https://shikshyasoftware.com.np/CoreApplicationandAPIService-
4617993073/api/school";
try {
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
if (extractedData == null) {
return;
}
if (response.statusCode == 200) {
print(extractedData);
}
HomePageModel loadedHomeData =
HomePageModel.fromJson(extractedData);
_hItem = loadedHomeData;
// EasyLoading.showSuccess("data fetched sucessfull");
notifyListeners();
} catch (e) {
rethrow;
}
}
}
getHomeData(BuildContext context) async {
const url =
"https://shikshyasoftware.com.np/CoreApplicationandAPIService-4617993073/api/school";
try {
// EasyLoading.show(status: 'Loading...');
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final extractedData = json.decode(response.body);
List loadedHomeData = extractedData;
_hItem = loadedHomeData.map((e) => HomePageModel.fromJson(e)).toList();
}
notifyListeners();
return _hItem;
} catch (e) {
rethrow;
}
}

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;
}
}

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();
}
}

I want to retrive each entity from following data in 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
}