I'm trying to map a list which has another list of objects but an error keep showing . Thank you for any help in advance
My Class
import 'Standing.dart';
class League {
String? country;
String? flag;
int? id;
String? logo;
String? name;
int? season;
List<List<Standing>>? standings;
League({this.country, this.flag, this.id, this.logo, this.name, this.season, this.standings});
factory League.fromJson(Map<String, dynamic> json) {
return League(
country: json['country'],
flag: json['flag'],
id: json['id'],
logo: json['logo'],
name: json['name'],
season: json['season'],
standings: json['standings'] != null ? (json['standings'] as List).map((i) => List<Standing>.from(i)).toList() : [],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['country'] = country;
data['flag'] = flag;
data['id'] = id;
data['logo'] = logo;
data['name'] = name;
data['season'] = season;
data['standings'] = standings?.map((v) => List<Standing>.from(v)).toList();
return data;
}
}
Standings Class
import 'All.dart';
import 'Away.dart';
import 'Home.dart';
import 'Team.dart';
class Standing {
All? all;
Away? away;
String? form;
int? goalsDiff;
String? group;
Home? home;
int? points;
int? rank;
String? status;
Team? team;
String? update;
Standing({this.all, this.away, this.form, this.goalsDiff, this.group, this.home, this.points, this.rank, this.status, this.team, this.update});
factory Standing.fromJson(Map<String, dynamic> json) {
return Standing(
all: json['all'] != null ? All.fromJson(json['all']) : null,
away: json['away'] != null ? Away.fromJson(json['away']) : null,
form: json['form'],
goalsDiff: json['goalsDiff'],
group: json['group'],
home: json['home'] != null ? Home.fromJson(json['home']) : null,
points: json['points'],
rank: json['rank'],
status: json['status'],
team: json['team'] != null ? Team.fromJson(json['team']) : null,
update: json['update'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['form'] = this.form;
data['goalsDiff'] = this.goalsDiff;
data['group'] = this.group;
data['points'] = this.points;
data['rank'] = this.rank;
data['status'] = this.status;
data['update'] = this.update;
final all = this.all;
if (all != null) {
data['all'] = all.toJson();
}
final away = this.away;
if (away != null) {
data['away'] = away.toJson();
}
final home = this.home;
if (home != null) {
data['home'] = home.toJson();
}
final team = this.team;
if (team != null) {
data['team'] = team.toJson();
}
return data;
}
}
data parsing
Future<StModel?> getStandings(int leagueId , int season) async {
HttpWithMiddleware httpClient = HttpWithMiddleware.build(middlewares: [
HttpLogger(logLevel: LogLevel.BODY),
]);
var fullUrl = "${Utils.BASE_URL}standings?league=$leagueId&season=$season";
var response = await httpClient.get(Uri.parse(fullUrl),headers: {
'x-rapidapi-host' : Utils.HOST,
'x-rapidapi-key' : Utils.KEY,
});
if(response.statusCode == 200){
var json = jsonDecode(response.body);
return StModel.fromJson(json);
} else {
return null;
}
}
Error
Change this:
factory League.fromJson(Map<String, dynamic> json) {
return League(
country: json['country'],
flag: json['flag'],
id: json['id'],
logo: json['logo'],
name: json['name'],
season: json['season'],
standings: json['standings'] != null ? (json['standings'] as List).map((i) => List<Standing>.from(i)).toList() : [],
);
}
to:
factory League.fromJson(Map<String, dynamic> json) {
List<List<Standing>> _standings = [];
for (var element in json['league']['standings'] as List) {
List<Standing> temp = [];
for (var item in element) {
temp.add(Standing.fromJson(item));
}
_standings.add(temp);
}
return League(
country: json['country'],
flag: json['flag'],
id: json['id'],
logo: json['logo'],
name: json['name'],
season: json['season'],
standings: _standings,
);
}
then use it like this:
if(response.statusCode == 200){
var json = jsonDecode(response.body);
return League.fromJson(json['response']);
} else {
return null;
}
Related
It's say Expected an identifier. In the late final groupId2 = GroupModel.fromDocumentSnapshot(doc: );
I don't what to put inside it. I am New to to flutter
The Screen:
late final groupId2 = GroupModel.fromDocumentSnapshot(doc: //Expected an identifier HERE);
This is the groupModel:
factory GroupModel.fromDocumentSnapshot({required DocumentSnapshot doc}) {
return GroupModel(
id: doc.id,
name: (doc.data() as Map<String, dynamic>)["name"],
leader: (doc.data() as Map<String, dynamic>)["leader"],
members: List<String>.from((doc.data() as Map<String, dynamic>)["members"]),
groupCreate: (doc.data() as Map<String, dynamic>)["groupCreate"],
);
}
Here is the model I created before. I hope it is helpful for you.
class ProductModel {
static const ID = "id";
static const IMAGE = "image";
static const NAME = "name";
static const BRAND = "brand";
static const PRICE = "price";
String? id;
String? image;
String? name;
String? brand;
int? price;
ProductModel(
{required this.id,
required this.image,
required this.name,
required this.brand,
required this.price});
factory ProductModel.fromFire(QueryDocumentSnapshot snapshot) {
return ProductModel.fromMap(snapshot as Map<String, dynamic>);
}
factory ProductModel.fromDocumentSnapshot({required DocumentSnapshot<Map<String,dynamic>> doc}){
// print(doc.data()!["id"]);
// print(doc.data()!["image"]);
// print(doc.data()!["name"]);
// print(doc.data()!["brand"]);
// print(doc.data()!["price"]);
return ProductModel(
id: doc.data()!["id"],
image: doc.data()!["image"],
name: doc.data()!["name"],
brand: doc.data()!["brand"],
price: doc.data()!["price"],
);
}
Map<String, dynamic> toJson() => {
'id': id,
'image': image,
'name': name,
'brand': brand,
'price': price,
};
ProductModel.fromMap(Map<String, dynamic> data) {
id = data[ID];
image = data[IMAGE];
name = data[NAME];
brand = data[BRAND];
price = data[PRICE];
}
}
Source Code: defining function
Future<void> getMessagesTestTest() async{
var aa = await _firestore.collection('ProductModel').snapshots().map((notes){
notesFromFirestore.clear();
for(final DocumentSnapshot<Map<String,dynamic>> doc in notes.docs){
log("start in loop");
log('doc.id == ${doc.id}');
// print("start in loop");
// print('doc.id == ${doc.id}');
notesFromFirestore.add(ProductModel.fromDocumentSnapshot(doc:doc));
// print(ProductModel.fromDocumentSnapshot(doc:doc));
}
// print(notesFromFirestore.first.id.toString());
return notesFromFirestore;});
// int count = await allData.length;
aa.listen(
(event) => print("Data Retrieved"),
);
// print(aa.length);
print( 'List Size = ${notesFromFirestore.length}');
var count = 0;
for (final ProductModel notesFromFirestoreA in notesFromFirestore) {
count++;
print('Loop Counter == ${count}');
print('Id == ${notesFromFirestoreA.id}');
print('Name == ${notesFromFirestoreA.name}');
print('Price == ${notesFromFirestoreA.price}');
print('Brand == ${notesFromFirestoreA.brand}');
print('image == ${notesFromFirestoreA.image}');
}
}
I cannot perform a data "toJson" operation of a model and the list in it.
main model
class ExampleData {
ExampleData({
this.name,
this.surname,
this.otherList,
});
String name;
String surname;
List<ExampleOtherData> otherList;
factory ExampleData.fromJson(Map<String, dynamic> json) =>
ExampleData(
name: json["name"] == null ? null : json["depoAdi"],
surname: json["surname"] == null ? null : json["aciklama"],
otherList: json["otherList"] == null
? null
: List<ExampleOtherData>.from(
json["otherList"].map((x) => ExampleOtherData.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name": name == null ? null : name,
"surname": surname == null ? null : surname,
"otherList": otherList == null
? null
: List<dynamic>.from(otherList.map((x) => x.toJson())),
};
}
sub model
list model linked to main model
class ExampleOtherData {
ExampleOtherData({
this.phone,
this.email
});
String phone;
String email;
factory ExampleOtherData.fromJson(Map<String, dynamic> json) =>
ExampleOtherData(
phone: json["phone"] == null ? null : json["phone"],
email: json["email"] == null ? null : json["email"],
);
Map<String, dynamic> toJson() => {
"phone": phone == null ? null : phone,
"email": email == null ? null : email,
};
}
How to add main model and list model in it?
How can I map the main model and the list model in it.
var newList = MainController.to.getExampleMain.map((value) => value.toJson());
await MainService.addExample(postBody: newList);
Thank you,
You just need to add toList() at the end of query.
var newList = MainController.to.getExampleMain.map((value) => value.toJson()).toList();
Basedon on model Class
json string
[{name: hi, surname: joji, otherlist: [{name: kl, surname: ja}, {name: lkl, surname: lja}]}, {name: hohi, surname: jpjoji, otherlist: [{name: kl, surname: ja}, {name: lkl, surname: lja}]}]
Dartpad
Sample Code
class MainController {
static List<ExampleData2> to() {
List<ExampleData2> data = [];
List<Otherlist> otherlist = [];
otherlist.add(new Otherlist(surname: "ja", name: "kl"));
otherlist.add(new Otherlist(surname: "lja", name: "lkl"));
data.add(
new ExampleData2(name: "hi", surname: "joji", otherlist: otherlist));
data.add(new ExampleData2(
name: "hohi", surname: "jpjoji", otherlist: otherlist));
return data;
}
}
void main() {
// ---------------------- json
var list = MainController.to().map((e) => e.toJson()).toList();
print(list);
var d = list.map((e) => ExampleData2.fromJson(e)).toList();
print(d);
}
class ExampleData2 {
String? name;
String? surname;
List<Otherlist>? otherlist;
ExampleData2({this.name, this.surname, this.otherlist});
ExampleData2.fromJson(Map<String, dynamic> json) {
name = json['name'];
surname = json['surname'];
if (json['otherlist'] != null) {
otherlist = <Otherlist>[];
json['otherlist'].forEach((v) {
otherlist!.add(new Otherlist.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['surname'] = this.surname;
if (this.otherlist != null) {
data['otherlist'] = this.otherlist!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Otherlist {
String? name;
String? surname;
Otherlist({this.name, this.surname});
Otherlist.fromJson(Map<String, dynamic> json) {
name = json['name'];
surname = json['surname'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['surname'] = this.surname;
return data;
}
}
You can generate required Model automatically from JSON structure, you can use online generators e.g. quicktype.io, just paste your JSON, select dart language and generate your model.
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;
}
}
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;
}
}
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
}