Receive data from API using Flutter - 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;
}
}

Related

How to access JSON via field?

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']),
);
}

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

I want to save list item with future bool is it possible?

Future<bool> login({username, password}) async {
var api = API();
_status = LoginStatus.loading;
notifyListeners();
var url = Uri.parse(api.baseUrl + api.auth);
final response = await http.post(
url,
body: jsonEncode({
"identifier": "$username",
"password": "$password",
}),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
if (response.statusCode == 200) {
final parsed = jsonDecode(response.body).cast<Map<String, dynamic>>();
parsed
.map<UserModel>((json) => UserModel.fromJson(json))
.toList();
final token = jsonDecode(response.body)['jwt'];
print(token);
await saveToken(token);
return true;
} else {
_status = LoginStatus.error;
_error = response.body;
notifyListeners();
return false;
}
}
Code Screen Shot
How Should I save this parsed JSON to UserModel? I have encountered many problems and figured out many things on my own but I am not yet able to add data to the model.
By the way I am using strapi as a back end and every api is working. And I amso use a website called json to dart converter so that my models are correct(As I Assume).
Please help !!!!!!!!!!!!
UserModel
class UserModel {
User user;
UserModel({this.user});
UserModel.fromJson(Map<String, dynamic> json) {
user = json['user'] != null ? new User.fromJson(json['user']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.user != null) {
data['user'] = this.user.toJson();
}
return data;
}
}
class User {
int id;
String username;
String email;
String provider;
bool confirmed;
bool blocked;
Role role;
String displayName;
String createdAt;
String updatedAt;
Avatar avatar;
List<UserCategories> userCategories;
User(
{this.id,
this.username,
this.email,
this.provider,
this.confirmed,
this.blocked,
this.role,
this.displayName,
this.createdAt,
this.updatedAt,
this.avatar,
this.userCategories});
User.fromJson(Map<String, dynamic> json) {
id = json['id'];
username = json['username'];
email = json['email'];
provider = json['provider'];
confirmed = json['confirmed'];
blocked = json['blocked'];
role = json['role'] != null ? new Role.fromJson(json['role']) : null;
displayName = json['displayName'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
avatar =
json['avatar'] != null ? new Avatar.fromJson(json['avatar']) : null;
if (json['user_categories'] != null) {
userCategories = new List<UserCategories>();
json['user_categories'].forEach((v) {
userCategories.add(new UserCategories.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['username'] = this.username;
data['email'] = this.email;
data['provider'] = this.provider;
data['confirmed'] = this.confirmed;
data['blocked'] = this.blocked;
if (this.role != null) {
data['role'] = this.role.toJson();
}
data['displayName'] = this.displayName;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
if (this.avatar != null) {
data['avatar'] = this.avatar.toJson();
}
if (this.userCategories != null) {
data['user_categories'] =
this.userCategories.map((v) => v.toJson()).toList();
}
return data;
}
}
class Role {
int id;
String name;
String description;
String type;
Role({this.id, this.name, this.description, this.type});
Role.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
description = json['description'];
type = json['type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['description'] = this.description;
data['type'] = this.type;
return data;
}
}
class Avatar {
int id;
String name;
String alternativeText;
String caption;
int width;
int height;
Formats formats;
String hash;
String ext;
String mime;
double size;
String url;
Null previewUrl;
String provider;
Null providerMetadata;
String createdAt;
String updatedAt;
Avatar(
{this.id,
this.name,
this.alternativeText,
this.caption,
this.width,
this.height,
this.formats,
this.hash,
this.ext,
this.mime,
this.size,
this.url,
this.previewUrl,
this.provider,
this.providerMetadata,
this.createdAt,
this.updatedAt});
Avatar.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
alternativeText = json['alternativeText'];
caption = json['caption'];
width = json['width'];
height = json['height'];
formats =
json['formats'] != null ? new Formats.fromJson(json['formats']) : null;
hash = json['hash'];
ext = json['ext'];
mime = json['mime'];
size = json['size'];
url = json['url'];
previewUrl = json['previewUrl'];
provider = json['provider'];
providerMetadata = json['provider_metadata'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['alternativeText'] = this.alternativeText;
data['caption'] = this.caption;
data['width'] = this.width;
data['height'] = this.height;
if (this.formats != null) {
data['formats'] = this.formats.toJson();
}
data['hash'] = this.hash;
data['ext'] = this.ext;
data['mime'] = this.mime;
data['size'] = this.size;
data['url'] = this.url;
data['previewUrl'] = this.previewUrl;
data['provider'] = this.provider;
data['provider_metadata'] = this.providerMetadata;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
class Formats {
Thumbnail thumbnail;
Formats({this.thumbnail});
Formats.fromJson(Map<String, dynamic> json) {
thumbnail = json['thumbnail'] != null
? new Thumbnail.fromJson(json['thumbnail'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.thumbnail != null) {
data['thumbnail'] = this.thumbnail.toJson();
}
return data;
}
}
class Thumbnail {
String name;
String hash;
String ext;
String mime;
int width;
int height;
double size;
Null path;
String url;
Thumbnail(
{this.name,
this.hash,
this.ext,
this.mime,
this.width,
this.height,
this.size,
this.path,
this.url});
Thumbnail.fromJson(Map<String, dynamic> json) {
name = json['name'];
hash = json['hash'];
ext = json['ext'];
mime = json['mime'];
width = json['width'];
height = json['height'];
size = json['size'];
path = json['path'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['hash'] = this.hash;
data['ext'] = this.ext;
data['mime'] = this.mime;
data['width'] = this.width;
data['height'] = this.height;
data['size'] = this.size;
data['path'] = this.path;
data['url'] = this.url;
return data;
}
}
class UserCategories {
int id;
String categoryName;
int usersPermissionsUser;
String publishedAt;
String createdAt;
String updatedAt;
UserCategories(
{this.id,
this.categoryName,
this.usersPermissionsUser,
this.publishedAt,
this.createdAt,
this.updatedAt});
UserCategories.fromJson(Map<String, dynamic> json) {
id = json['id'];
categoryName = json['categoryName'];
usersPermissionsUser = json['users_permissions_user'];
publishedAt = json['published_at'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['categoryName'] = this.categoryName;
data['users_permissions_user'] = this.usersPermissionsUser;
data['published_at'] = this.publishedAt;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}
The UserModel.fromJson method will only work if the response.body content is a User, so to fix your issue, instead of using UserModel.fromJson on the response.body json decoded variable, rather use the fromJson() function on data that you are sure will conform to your class definition.
For example:
class User{
final String name;
final String surname;
final String email;
User({this.name, this.surname, this.email});
factory User.fromJson(Map<String,dynamic> json){
return User(
'name': json['name'],
'surname': json['surname'],
'email': json['email']
);
}
}
The json response that is recieved from the api:
{
"name" : "John",
"surname": "Smith",
"email": "johnsmith#mail.com"
}
In your function, decode response and cast to the User model class:
final parsed = jsonDecode(response.body); // or Map<String,dynamic> parsed = jsonDecode(response.body);
User user = User.fromJson(parsed)

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
}