I can successfully display PartnerName, PartnerAddress which are in PartnerData[]. Now inside PartnerData there is another ArrayList DayList[] how can I print those arrayList data DayName,TimeFrom etc etc??
{
"Status": "1",
"Message": "",
"Data": {
"EncDietId": "pEl2B9kuumKRxIxLJO76eQ==",
"DietName": "dietcian2",
"Email": null,
"Phone": null,
"AlternatePhone": null,
"Image": "http://myapi/Doctor/65AUCUE8RTD2UKBRV.jpg",
"Description": null,
"Fee": null,
"DiscountedFee": null,
"BookingFee": null,
"VisitDay": null,
"TimeFrom": null,
"TimeTo": null
},
"PartnerData": [
{
"PartnerId": "13",
"EncPartnerId": "65gtodyhbtdInTsJWr1ZkA==",
"PartnerName": "Rasomoy pvt. Hospital",
"PartnerAddress": "Kol,Kol,Kol,Wb",
"Fee": "1200",
"DiscountedFee": "900",
"BookingFee": "500",
"DayList": [
{
"DayName": "Wednesday",
"TimeFrom": "10:00",
"TimeTo": "16:00"
},
{
"DayName": "Friday",
"TimeFrom": "10:00",
"TimeTo": "16:00"
},
{
"DayName": "Saturday",
"TimeFrom": "10:00",
"TimeTo": "16:00"
}
]
}
]
}
My Api
Future<List<PartnerDatum>> dietcianDetailsApi() async {
var jsonResponse;
var response = await http.post(
Uri.parse("http://ggmyapin/api/api/Diet"),
body: ({
'EncId': encDietcianIdRef,
}));
if (response.statusCode == 200) {
print("Correct");
print(response.body);
jsonResponse = json.decode(response.body.toString());
print(jsonResponse);
DietDetailsModel dataModel = dietDetailsModelFromJson(response.body);
print(dataModel.partnerData.length);
for (final item in dataModel.partnerData)
print(item.partnerName);
List<PartnerDatum> arrData =dataModel.partnerData;
return arrData;
} else {
print("Wrong Url");
print(response.body);
throw Exception("Faild to fetch");
}
}
Displying in ListView. For now Successfully can display data PartnerName which are in PartnerData[] . I'm trying to display DayList[] data too. What will be the syntax for this?
Container(
height: blockSizeVertical*30,//38
child: FutureBuilder(
future: dietcianDetailsApi(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
// if (snapshot.connectionState !=ConnectionState.done) {
// return CircularProgressIndicator();
// }
if (snapshot.hasError) {
return Text("Somthing went wrong");
}
if (snapshot.hasData) {
return ListView.builder(
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) =>
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
width: blockSizeHorizontal*80,
margin: EdgeInsets.all(10),
child: Stack(children: [
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: blockSizeVertical*0.5),
Text(
'PartnerName : ${snapshot.data[index].partnerName}',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: blockSizeHorizontal*3.5,
fontFamily: 'Poppins',
color: Theme.of(context).primaryColor,
),
textAlign: TextAlign.center,
),
Model Class
// To parse this JSON data, do
//
// final dietDetailsModel = dietDetailsModelFromJson(jsonString);
import 'package:meta/meta.dart';
import 'dart:convert';
DietDetailsModel dietDetailsModelFromJson(String str) => DietDetailsModel.fromJson(json.decode(str));
String dietDetailsModelToJson(DietDetailsModel data) => json.encode(data.toJson());
class DietDetailsModel {
DietDetailsModel({
required this.status,
required this.message,
required this.data,
required this.partnerData,
});
String status;
String message;
Data data;
List<PartnerDatum> partnerData;
factory DietDetailsModel.fromJson(Map<String, dynamic> json) => DietDetailsModel(
status: json["Status"],
message: json["Message"],
data: Data.fromJson(json["Data"]),
partnerData: List<PartnerDatum>.from(json["PartnerData"].map((x) => PartnerDatum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Status": status,
"Message": message,
"Data": data.toJson(),
"PartnerData": List<dynamic>.from(partnerData.map((x) => x.toJson())),
};
}
class Data {
Data({
required this.encDietId,
required this.dietName,
required this.email,
required this.phone,
required this.alternatePhone,
required this.image,
required this.description,
required this.fee,
required this.discountedFee,
required this.bookingFee,
required this.visitDay,
required this.timeFrom,
required this.timeTo,
});
String encDietId;
String dietName;
dynamic email;
dynamic phone;
dynamic alternatePhone;
String image;
dynamic description;
dynamic fee;
dynamic discountedFee;
dynamic bookingFee;
dynamic visitDay;
dynamic timeFrom;
dynamic timeTo;
factory Data.fromJson(Map<String, dynamic> json) => Data(
encDietId: json["EncDietId"],
dietName: json["DietName"],
email: json["Email"],
phone: json["Phone"],
alternatePhone: json["AlternatePhone"],
image: json["Image"],
description: json["Description"],
fee: json["Fee"],
discountedFee: json["DiscountedFee"],
bookingFee: json["BookingFee"],
visitDay: json["VisitDay"],
timeFrom: json["TimeFrom"],
timeTo: json["TimeTo"],
);
Map<String, dynamic> toJson() => {
"EncDietId": encDietId,
"DietName": dietName,
"Email": email,
"Phone": phone,
"AlternatePhone": alternatePhone,
"Image": image,
"Description": description,
"Fee": fee,
"DiscountedFee": discountedFee,
"BookingFee": bookingFee,
"VisitDay": visitDay,
"TimeFrom": timeFrom,
"TimeTo": timeTo,
};
}
class PartnerDatum {
PartnerDatum({
required this.partnerId,
required this.encPartnerId,
required this.partnerName,
required this.partnerAddress,
required this.fee,
required this.discountedFee,
required this.bookingFee,
required this.dayList,
});
String partnerId;
String encPartnerId;
String partnerName;
String partnerAddress;
String fee;
String discountedFee;
String bookingFee;
List<DayList> dayList;
factory PartnerDatum.fromJson(Map<String, dynamic> json) => PartnerDatum(
partnerId: json["PartnerId"],
encPartnerId: json["EncPartnerId"],
partnerName: json["PartnerName"],
partnerAddress: json["PartnerAddress"],
fee: json["Fee"],
discountedFee: json["DiscountedFee"],
bookingFee: json["BookingFee"],
dayList: List<DayList>.from(json["DayList"].map((x) => DayList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"PartnerId": partnerId,
"EncPartnerId": encPartnerId,
"PartnerName": partnerName,
"PartnerAddress": partnerAddress,
"Fee": fee,
"DiscountedFee": discountedFee,
"BookingFee": bookingFee,
"DayList": List<dynamic>.from(dayList.map((x) => x.toJson())),
};
}
class DayList {
DayList({
required this.dayName,
required this.timeFrom,
required this.timeTo,
});
String dayName;
String timeFrom;
String timeTo;
factory DayList.fromJson(Map<String, dynamic> json) => DayList(
dayName: json["DayName"],
timeFrom: json["TimeFrom"],
timeTo: json["TimeTo"],
);
Map<String, dynamic> toJson() => {
"DayName": dayName,
"TimeFrom": timeFrom,
"TimeTo": timeTo,
};
}
try below code hope its helpful to you
You can use string indexes to access these properties:
print(result['PartnerData'][0]['PartnerName']); // Rasomoy pvt. Hospital
print(result['PartnerData'][0]['PartnerAddress']); // Kol,Kol,Kol,Wb
Now go to Flutter documentation here:
The documentation also refers to the such model classes here :
Related
what should I do to display this data
"result": [
{
"department_id": null,
"crime_time_id": "5562f55f-54aa-4e94-9f6c-9ce25d9e3fd9",
"village_id": "3174031001",
"cases": 3,
"villages": 3,
"target_id": null,
"department": null,
"crime_time": {
"id": "5562f55f-54aa-4e94-9f6c-9ce25d9e3fd9",
"name": "00.00 - 02.00"
},
"village": {
"id": "3174031001",
"name": "MAMPANG PRAPATAN"
}
},
{
"department_id": null,
"crime_time_id": "ca56d7a3-fdea-446a-a628-cc7091f314de",
"village_id": "1604082010",
"cases": 1,
"villages": 1,
"target_id": null,
"department": null,
"crime_time": {
"id": "ca56d7a3-fdea-446a-a628-cc7091f314de",
"name": "06.00 - 08.00"
},
"village": {
"id": "1604082010",
"name": "TANJUNG SIRIH"
}
}
]
I have try to handle this but there is some display error
'expected a value of type 'int?' but got one of type 'String' and
'the method fromjson isnt defined for the type data. try correcting the name to the name of an exsiting method
this my model:
class rangkumanKasus {
int? department_id;
String? crime_time_id;
int? village_id;
int? cases;
int? villages;
int? target_id;
String? department;
final Crime_Time crime_time;
final Village village;
rangkumanKasus({
this.department_id,
this.crime_time_id,
this.village_id,
this.cases,
this.villages,
this.target_id,
this.department,
required this.crime_time,
required this.village,
});
factory rangkumanKasus.fromJson(Map<String, dynamic> json) {
return rangkumanKasus(
department_id: json["department_id"],
crime_time_id: json['crime_time_id'],
village_id: json['village_id'],
cases: json['cases'],
villages: json['villages'],
target_id: json['target_id'],
department: json['department'],
crime_time: Crime_Time.fromJson(json['crime_time']),
village: Village.fromJson(json['village']),
);
}
}
class Crime_Time {
int? id;
String? name;
Crime_Time({
this.id,
this.name,
});
factory Crime_Time.fromJson(Map<dynamic, dynamic> json) {
return Crime_Time(
id: json['id'],
name: json['name'],
);
}
}
class Village {
int? id;
String? name;
Village({
this.id,
this.name,
});
factory Village.fromJson(Map<dynamic, dynamic> json) {
return Village(
id: json['id'],
name: json['name'],
);
}
}
and this how I try to display
Container(
child: FutureBuilder<List<rangkumanKasus>>(
future: listData,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<rangkumanKasus> isiData = snapshot.data!;
return ListView.builder(
shrinkWrap: true,
itemCount: isiData.length,
itemBuilder: (context, index) {
return Container(
child: Text(
isiData[index].crime_time.name!,
style: TextStyle(color: Colors.red),
));
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return const CircularProgressIndicator();
}),
i have a super long json file to be parsed but once i fetch it in a FutureBuilder it keeps erroring that i used a null check operator on a null value, to me seems like i don't know the logic..!
here's the simplified json:
{
"city": {
"Name": "oklahoma",
"Month": [
{
"number": "01",
"day": [
{
"number": "01",
"employee": "jesse m."
},
{
"number": "02",
"employee": "john s."
},
{
"number": "03",
"name": "tyler r."
}
]
},
{
"number": "02",
"day": [
{
"number": "01",
"employee": "mat w."
},
{
"number": "02",
"employee": "may j."
},
{
"number": "03",
"name": "eric r."
}
]
}
]
}
}
note that i have one city and the json has the data of every individual days throughout the whole year
and here's the model:
// To parse this JSON data, do
//
// final company = companyFromJson(jsonString);
import 'dart:convert';
company companyFromJson(String str) => company.fromJson(json.decode(str));
String companyToJson(company data) => json.encode(data.toJson());
class company {
company({
required this.city,
});
City city;
factory company.fromJson(Map<String, dynamic> json) => company(
city: City.fromJson(json["city"]),
);
Map<String, dynamic> toJson() => {
"city": city.toJson(),
};
}
class City {
City({
required this.name,
required this.month,
});
String name;
List<Month> month;
factory City.fromJson(Map<String, dynamic> json) => City(
name: json["Name"],
month: List<Month>.from(json["Month"].map((x) => Month.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Name": name,
"Month": List<dynamic>.from(month.map((x) => x.toJson())),
};
}
class Month {
Month({
required this.number,
required this.day,
});
String number;
List<Day> day;
factory Month.fromJson(Map<String, dynamic> json) => Month(
number: json["number"],
day: List<Day>.from(json["day"].map((x) => Day.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"number": number,
"day": List<dynamic>.from(day.map((x) => x.toJson())),
};
}
class Day {
Day({
required this.number,
required this.employee
});
String number;
String employee;
factory Day.fromJson(Map<String, dynamic> json) => Day(
number: json["number"],
employee: json["employee"]
);
Map<String, dynamic> toJson() => {
"number": number,
"employee": employee
};
}
this is the parsing method:
Future<List<Day>> getCompanyEmployee () async {
String jsonString = await DefaultAssetBundle.of(context).loadString('assets/json/OklahomaEmployee.json');
List<dynamic> result = jsonDecode(jsonString);
List<Day> Company = result.map((e) => Day.fromJson(e)).toList();
return Company;
}
this is the implementation:
FutureBuilder<List<Day>>(
future: getCompanyEmployee(),
builder: (context, snapshot) {
var itemList = snapshot.data;
return GridView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
),
itemCount: itemList!.length,
itemBuilder: (BuildContext context, index) {
var itemData = itemList[index];
return ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Container(
height: 10,
color: Colors.white,
width: 10,
child: Center(
child: Column(
children: [
Text(
'employee',
style: TextStyle(fontSize: 15),
),
Text(itemData.employee),
Image.asset(
'assets/Pictures/employees.png',
height: 70,
)
],
),
),
),
);
},
);
},
)
In your FutureBuilder, you just assume the future has already completed. The point of a FutureBuilder is that it has not and you need to deal with that.
You need to account for the fact that your Futurebuilder needs to build something even if the future has not yet completed. The simplest thing to make that happen is to show a CircularProgressIndicator as long as you don't have data.
See What is a Future and how do I use it? for an example of how to do that.
How to display DietName which is under Data? I can display the item which is under PartnerData[] But what is the syntax just to display DietName?
{
"Status": "1",
"Message": "",
"Data": {
"EncDietId": "pEl2B9kuumKRxIxLJO76eQ==",
"DietName": "dietcian2",
"Email": null,
"Phone": null,
"AlternatePhone": null,
"Image": "http://mjjjjctor/65AUEYMCUE8RTD2UKBRV.jpg",
"Description": null,
"Fee": null,
"DiscountedFee": null,
"BookingFee": null,
"VisitDay": null,
"TimeFrom": null,
"TimeTo": null
},
"PartnerData": [
{
"PartnerId": "13",
"EncPartnerId": "65gtodyhbtdInTsJWr1ZkA==",
"PartnerName": "Rasomoy pvt. Hospital",
"PartnerAddress": "Kol,Kol,Kol,Wb",
"Fee": "1200",
"DiscountedFee": "900",
"BookingFee": "500",
"DayList": [
{
"DayName": "Wednesday",
"TimeFrom": "10:00",
"TimeTo": "16:00"
},
{
"DayName": "Friday",
"TimeFrom": "10:00",
"TimeTo": "16:00"
},
{
"DayName": "Saturday",
"TimeFrom": "10:00",
"TimeTo": "16:00"
}
]
}
]
}
Model class:
DietDetailsModel dietDetailsModelFromJson(String str) => DietDetailsModel.fromJson(json.decode(str));
String dietDetailsModelToJson(DietDetailsModel data) => json.encode(data.toJson());
class DietDetailsModel {
DietDetailsModel({
required this.status,
required this.message,
required this.data,
required this.partnerData,
});
String status;
String message;
Data data;
List<PartnerDatum> partnerData;
factory DietDetailsModel.fromJson(Map<String, dynamic> json) => DietDetailsModel(
status: json["Status"],
message: json["Message"],
data: Data.fromJson(json["Data"]),
partnerData: List<PartnerDatum>.from(json["PartnerData"].map((x) => PartnerDatum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Status": status,
"Message": message,
"Data": data.toJson(),
"PartnerData": List<dynamic>.from(partnerData.map((x) => x.toJson())),
};
}
class Data {
Data({
required this.encDietId,
required this.dietName,
required this.email,
required this.phone,
required this.alternatePhone,
required this.image,
required this.description,
required this.fee,
required this.discountedFee,
required this.bookingFee,
required this.visitDay,
required this.timeFrom,
required this.timeTo,
});
String encDietId;
String dietName;
dynamic email;
dynamic phone;
dynamic alternatePhone;
String image;
dynamic description;
dynamic fee;
dynamic discountedFee;
dynamic bookingFee;
dynamic visitDay;
dynamic timeFrom;
dynamic timeTo;
factory Data.fromJson(Map<String, dynamic> json) => Data(
encDietId: json["EncDietId"],
dietName: json["DietName"],
email: json["Email"],
phone: json["Phone"],
alternatePhone: json["AlternatePhone"],
image: json["Image"],
description: json["Description"],
fee: json["Fee"],
discountedFee: json["DiscountedFee"],
bookingFee: json["BookingFee"],
visitDay: json["VisitDay"],
timeFrom: json["TimeFrom"],
timeTo: json["TimeTo"],
);
Map<String, dynamic> toJson() => {
"EncDietId": encDietId,
"DietName": dietName,
"Email": email,
"Phone": phone,
"AlternatePhone": alternatePhone,
"Image": image,
"Description": description,
"Fee": fee,
"DiscountedFee": discountedFee,
"BookingFee": bookingFee,
"VisitDay": visitDay,
"TimeFrom": timeFrom,
"TimeTo": timeTo,
};
}
My API
Future<List<PartnerDatum>> dietcianDetailsApi() async {
var jsonResponse;
var response = await http.post(
Uri.parse("http://mjjjjapi/DietDetails"),
body: ({
'EncId': encDietcianIdRef,
}));
if (response.statusCode == 200) {
print("Correct");
print(response.body);
jsonResponse = json.decode(response.body.toString());
print(jsonResponse);
//Navigator.push(context, MaterialPageRoute(builder: (context)=>AfterSearchPage(rresponse: SearchApiResponse.fromJson(jsonResponse))));
DietDetailsModel dataModel = dietDetailsModelFromJson(response.body);
print(dataModel.partnerData.length);
for (final item in dataModel.partnerData)
print(item.partnerName);
List<PartnerDatum> arrData =dataModel.partnerData;
// print(arrData[1].partnerName);
return arrData;
} else {
print("Wrong Url");
print(response.body);
throw Exception("Faild to fetch");
}
//return AllDietician();
}
Printing My PartnerData items . But How to display DietName which is inside Data?
class DietcianDetailsPage extends StatefulWidget {
var encDietcianId;
DietcianDetailsPage(this.encDietcianId);
#override
_DietcianDetailsPageState createState() => _DietcianDetailsPageState(this.encDietcianId);
}
class _DietcianDetailsPageState extends State<DietcianDetailsPage> {
var encDietcianIdRef;// Need to pass is encId as a parameter in dietcianDetails Api
_DietcianDetailsPageState(this.encDietcianIdRef);
#override
void initState() {
dietcianDetailsApi();
super.initState();
}
#override
Widget build(BuildContext context) {
var screenWidth = MediaQuery.of(context).size.width;
var screenHeight = MediaQuery.of(context).size.height;
var blockSizeHorizontal = (screenWidth/100);
var blockSizeVertical= (screenHeight/100);
return Scaffold(
appBar: AppBar(
elevation: 0.0,
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.topRight,
colors: [
Theme.of(context).primaryColor,
Theme.of(context).accentColor
],
),
),
),
title: Center(
child: Image.asset(
"assets/images/medbo.png",
fit: BoxFit.contain,
height: 52,),
),
//toolbarHeight: 88,
actions: [
IconButton(onPressed: () => {}, icon: Icon(Icons.more_vert,size: 0.1,),),
],
),
body: Container(
child: Column(
children: [
Text(
""
),
//========================================================================
Container(
height: blockSizeVertical*30,//38
//color: Colors.blueAccent,
child: FutureBuilder(
future: dietcianDetailsApi(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
// if (snapshot.connectionState !=ConnectionState.done) {
// return CircularProgressIndicator();
// }
if (snapshot.hasError) {
return Text("Somthing went wrong");
}
if (snapshot.hasData) {
return ListView.builder(
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) =>
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
width: blockSizeHorizontal*80,
margin: EdgeInsets.all(10),
child: Stack(children: [
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(//====================images
padding: const EdgeInsets.all(5.0),
),
SizedBox(height: blockSizeVertical*0.5),
Text(
'PartnerName : ${snapshot.data[index].partnerName}',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: blockSizeHorizontal*3.5,
fontFamily: 'Poppins',
color: Theme.of(context).primaryColor,
),
textAlign: TextAlign.center,
),
The problem is dietcianDetailsApi because you return a List< PartnerDatum> and this model doesn't contains a DietName.
First solution is modify your function (dietcianDetailsApi), needs modify the data type that this function return, because the DietDetailsModel model contains both variables that you need.
Example:
Inside of dietcianDetailsApi you can assign the value, like this:
Future<DietDetailsModel> dietcianDetailsApi() async {
var jsonResponse;
var response = await http.post(
Uri.parse("http://medbo.digitalicon.in/api/medboapi/DietDetails"),
body: ({
'EncId': encDietcianIdRef,
}));
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body.toString());
DietDetailsModel dataModel = dietDetailsModelFromJson(response.body);
return dataModel
} else {
print("Wrong Url");
print(response.body);
throw Exception("Faild to fetch");
}
Finally, you can replace your FutureBuilder for this:
FutureBuilder(
future: dietcianDetailsApi(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Text("Somthing went wrong");
}
if (snapshot.hasData) {
var dietDetails = snapshot.data;
print('PartnerData: ${dietDetails.partnerData}');
print('DietName: ${dietDetails.data.dietName}');
// ADD YOUR CODE
}
}
),
Your Future is returning only the partnerData while it could as well return the whole DietDetailsModel in one object.
If you return the DietDetailsModel dataModel you could then consume the response in DietcianDetailsPage. Your ListView would use dataModel.data.partnerData but you could also access dataModel.data.data.
I hope I did not mix up the fields in your code.
I'm trying to display DietName from Data{} || PartnerName from PartnerData[] || DayName from DayList[]. As those data inside another ArrayList of data I'm facing problem with correct syntax to display those data.
{
"Status": "1",
"Message": "",
"Data": {
"EncDietId": "pEl2B9kuumKRxIxLJO76eQ==",
"DietName": "dietcian2",
"Email": null,
"Phone": null,
"AlternatePhone": null,
"Image": "http://mypain/Doctor/65AUEYyryTD2UKBRV.jpg",
"Description": null,
"Fee": null,
"DiscountedFee": null,
"BookingFee": null,
"VisitDay": null,
"TimeFrom": null,
"TimeTo": null
},
"PartnerData": [
{
"PartnerId": "13",
"EncPartnerId": "65gtodyhbtdInTsJWr1ZkA==",
"PartnerName": "Rasomoy pvt. Hospital",
"PartnerAddress": "Kol,Kol,Kol,Wb",
"Fee": "1200",
"DiscountedFee": "900",
"BookingFee": "500",
"DayList": [
{
"DayName": "Wednesday",
"TimeFrom": "10:00",
"TimeTo": "16:00"
},
{
"DayName": "Friday",
"TimeFrom": "10:00",
"TimeTo": "16:00"
},
{
"DayName": "Saturday",
"TimeFrom": "10:00",
"TimeTo": "16:00"
}
]
}
]
}
My API function .
Future<List<PartnerDatum>> dietcianDetailsApi() async {
var jsonResponse;
var response = await http.post(
Uri.parse("http://myapin/api/api/DietDetails"),
body: ({
'EncId ': pEl2tetIxLJO76eQ== //(encDietcianIdRef)
}));
if (response.statusCode == 200) {
print("Correct");
print(response.body);
jsonResponse = json.decode(response.body.toString());
print(jsonResponse);
DietDetailsModel dataModel = dietDetailsModelFromJson(response.body);
print(dataModel.partnerData.length);
for (final item in dataModel.partnerData)
print(item.partnerName);
List<PartnerDatum> arrData =dataModel.partnerData;
print(arrData[1].partnerName);
return arrData;
} else {
print("Wrong Url");
print(response.body);
throw Exception("Faild to fetch");
}
//return AllDietician();
}
Try to Print my JSON data in ListView builder .
Container(
height: blockSizeVertical*30,//38
//color: Colors.blueAccent,
child: FutureBuilder(
future: dietcianDetailsApi(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
// if (snapshot.connectionState !=ConnectionState.done) {
// return CircularProgressIndicator();
// }
if (snapshot.hasError) {
return Text("Somthing went wrong");
}
if (snapshot.hasData) {
return ListView.builder(
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) =>
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
width: blockSizeHorizontal*80,
margin: EdgeInsets.all(10),
child: Stack(children: [
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: blockSizeVertical*0.5),
Text(
'${snapshot.data[index].partnerName}',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: blockSizeHorizontal*3.5,
fontFamily: 'Poppins',
color: Theme.of(context).primaryColor,
),
textAlign: TextAlign.center,
),
SizedBox(height: blockSizeVertical*0.8),
Container(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Center(
child: Text(
'PartnerAddress : ${snapshot.data[index].partnerAddress} Fee: ${snapshot.data[index].fee} || DiscountedFee: ${snapshot.data[index].discountedFee} ',//put email
style: TextStyle(
fontFamily: 'Poppins',
fontSize: blockSizeHorizontal*2.5,
color: Theme.of(context).primaryColor),
textAlign: TextAlign.center,
maxLines: 4,
),
),
),
]
),
Positioned(
bottom: 5,
left: 2,
child: Padding(
padding: const EdgeInsets.only(left:15.0, bottom: 5),
child: InkWell(
onTap: () {
},
child: Container(
alignment: Alignment.center,
height: blockSizeVertical*5,
width: blockSizeHorizontal*30,
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(10),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.topRight,
colors: [
Theme.of(context).primaryColor,
Theme.of(context).accentColor
],
),
),
child: Text(
'Show Details',
style: TextStyle(
color: Colors.white,
fontSize: blockSizeHorizontal*2.7,
fontWeight: FontWeight.bold,
fontFamily: 'Poppins',
),
),
),
),
),
),
]),
),
);
}
return Text("Error while calling");
},
),
),
My Model class
import 'package:meta/meta.dart';
import 'dart:convert';
DietDetailsModel dietDetailsModelFromJson(String str) => DietDetailsModel.fromJson(json.decode(str));
String dietDetailsModelToJson(DietDetailsModel data) => json.encode(data.toJson());
class DietDetailsModel {
DietDetailsModel({
required this.status,
required this.message,
required this.data,
required this.partnerData,
});
String status;
String message;
Data data;
List<PartnerDatum> partnerData;
factory DietDetailsModel.fromJson(Map<String, dynamic> json) => DietDetailsModel(
status: json["Status"],
message: json["Message"],
data: Data.fromJson(json["Data"]),
partnerData: List<PartnerDatum>.from(json["PartnerData"].map((x) => PartnerDatum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Status": status,
"Message": message,
"Data": data.toJson(),
"PartnerData": List<dynamic>.from(partnerData.map((x) => x.toJson())),
};
}
class Data {
Data({
required this.encDietId,
required this.dietName,
required this.email,
required this.phone,
required this.alternatePhone,
required this.image,
required this.description,
required this.fee,
required this.discountedFee,
required this.bookingFee,
required this.visitDay,
required this.timeFrom,
required this.timeTo,
});
String encDietId;
String dietName;
dynamic email;
dynamic phone;
dynamic alternatePhone;
String image;
dynamic description;
dynamic fee;
dynamic discountedFee;
dynamic bookingFee;
dynamic visitDay;
dynamic timeFrom;
dynamic timeTo;
factory Data.fromJson(Map<String, dynamic> json) => Data(
encDietId: json["EncDietId"],
dietName: json["DietName"],
email: json["Email"],
phone: json["Phone"],
alternatePhone: json["AlternatePhone"],
image: json["Image"],
description: json["Description"],
fee: json["Fee"],
discountedFee: json["DiscountedFee"],
bookingFee: json["BookingFee"],
visitDay: json["VisitDay"],
timeFrom: json["TimeFrom"],
timeTo: json["TimeTo"],
);
Map<String, dynamic> toJson() => {
"EncDietId": encDietId,
"DietName": dietName,
"Email": email,
"Phone": phone,
"AlternatePhone": alternatePhone,
"Image": image,
"Description": description,
"Fee": fee,
"DiscountedFee": discountedFee,
"BookingFee": bookingFee,
"VisitDay": visitDay,
"TimeFrom": timeFrom,
"TimeTo": timeTo,
};
}
class PartnerDatum {
PartnerDatum({
required this.partnerId,
required this.encPartnerId,
required this.partnerName,
required this.partnerAddress,
required this.fee,
required this.discountedFee,
required this.bookingFee,
required this.dayList,
});
String partnerId;
String encPartnerId;
String partnerName;
String partnerAddress;
String fee;
String discountedFee;
String bookingFee;
List<DayList> dayList;
factory PartnerDatum.fromJson(Map<String, dynamic> json) => PartnerDatum(
partnerId: json["PartnerId"],
encPartnerId: json["EncPartnerId"],
partnerName: json["PartnerName"],
partnerAddress: json["PartnerAddress"],
fee: json["Fee"],
discountedFee: json["DiscountedFee"],
bookingFee: json["BookingFee"],
dayList: List<DayList>.from(json["DayList"].map((x) => DayList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"PartnerId": partnerId,
"EncPartnerId": encPartnerId,
"PartnerName": partnerName,
"PartnerAddress": partnerAddress,
"Fee": fee,
"DiscountedFee": discountedFee,
"BookingFee": bookingFee,
"DayList": List<dynamic>.from(dayList.map((x) => x.toJson())),
};
}
class DayList {
DayList({
required this.dayName,
required this.timeFrom,
required this.timeTo,
});
String dayName;
String timeFrom;
String timeTo;
factory DayList.fromJson(Map<String, dynamic> json) => DayList(
dayName: json["DayName"],
timeFrom: json["TimeFrom"],
timeTo: json["TimeTo"],
);
Map<String, dynamic> toJson() => {
"DayName": dayName,
"TimeFrom": timeFrom,
"TimeTo": timeTo,
};
}
Since your deserialization seems to work, this is how you would access the first dayname in your list:
final firstPartnerDatum = myDietDetailsModel.partnerData[0];
final dayList = firstPartnerDatum.dayList[0];
final dayName = dayList.dayName;
I'm able to parse the JSON using following code,
Map<String, dynamic> map = jsonDecode(response.body); // import 'dart:convert';
List<dynamic> datalist = map['data'];
I got List dynamic but i need data list
My problem is if I get product items in data list then how should i parse the JSON. I got stuck here.
When it comes to nested array of JSON, how to parse it.
**
{
"status": 0,
"message": "Product Not Found",
"data": [{
"id": "1",
"product_name": "Pet 0.5",
"qty": "500",
"unit": "ml",
"product_img": "SRC.jpg",
"description": "sgsdgdfhdfhh",
"sale_price": "100",
"donation_amt": "10"
},
{
"id": "7",
"product_name": "Pet 1l",
"qty": "1",
"unit": "l",
"product_img": "SRC1.jpg",
"description": "dgdg",
"sale_price": "20",
"donation_amt": "1"
}
]
}
**
My dart code for the JSON
class ProductList {
int status;
String message;
List<Data> data;
ProductList({this.status, this.message, this.data});
ProductList.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
if (json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['message'] = this.message;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String id;
String productName;
String qty;
String unit;
String productImg;
String description;
String salePrice;
String donationAmt;
Data(
{this.id,
this.productName,
this.qty,
this.unit,
this.productImg,
this.description,
this.salePrice,
this.donationAmt});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
productName = json['product_name'];
qty = json['qty'];
unit = json['unit'];
productImg = json['product_img'];
description = json['description'];
salePrice = json['sale_price'];
donationAmt = json['donation_amt'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['product_name'] = this.productName;
data['qty'] = this.qty;
data['unit'] = this.unit;
data['product_img'] = this.productImg;
data['description'] = this.description;
data['sale_price'] = this.salePrice;
data['donation_amt'] = this.donationAmt;
return data;
}
}
This is the code below for the drop down list. We need to populate the drop down with the product name and id. The product name and id fields are there in the data part of the JSON
Padding(
padding: const EdgeInsets.fromLTRB(25.0, 20.0, 0, 0),
child: Container(
width: 160,
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
border: Border.all(
color: Colors.red,
style: BorderStyle.solid,
width: 0.80),
),
child: DropdownButton<Product>(
value: selectedUser,
icon: Padding(
padding: const EdgeInsets.only(left:15.0),
child: Icon(Icons.arrow_drop_down),
),
iconSize: 25,
underline: SizedBox(),
onChanged: (Product newValue) {
setState(() {
selectedUser = newValue;
});
},
items: users.map((Product user) {
return DropdownMenuItem<Product>(
value: user,
child: Padding(
padding:
const EdgeInsets.only(left: 10.0),
child: Text(
user.name,
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);
}).toList()),
),
),
So as you Described i have made some changes and loaded you json locally, you can make a api call and then everything is the same:
{
"status": 0,
"message": "Product Not Found",
"data": [
{
"id": "1",
"product_name": "Pet 0.5",
"qty": "500",
"unit": "ml",
"product_img": "SRC.jpg",
"description": "sgsdgdfhdfhh",
"sale_price": "100",
"donation_amt": "10"
},
{
"id": "7",
"product_name": "Pet 1l",
"qty": "1",
"unit": "l",
"product_img": "SRC1.jpg",
"description": "dgdg",
"sale_price": "20",
"donation_amt": "1"
}
]
}
json you provided
// To parse this JSON data, do
//
// final productList = productListFromJson(jsonString);
import 'dart:convert';
ProductList productListFromJson(String str) =>
ProductList.fromJson(json.decode(str));
String productListToJson(ProductList data) => json.encode(data.toJson());
class ProductList {
int status;
String message;
List<Datum> data;
ProductList({
this.status,
this.message,
this.data,
});
factory ProductList.fromJson(Map<String, dynamic> json) => ProductList(
status: json["status"],
message: json["message"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
String id;
String productName;
String qty;
String unit;
String productImg;
String description;
String salePrice;
String donationAmt;
Datum({
this.id,
this.productName,
this.qty,
this.unit,
this.productImg,
this.description,
this.salePrice,
this.donationAmt,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
productName: json["product_name"],
qty: json["qty"],
unit: json["unit"],
productImg: json["product_img"],
description: json["description"],
salePrice: json["sale_price"],
donationAmt: json["donation_amt"],
);
Map<String, dynamic> toJson() => {
"id": id,
"product_name": productName,
"qty": qty,
"unit": unit,
"product_img": productImg,
"description": description,
"sale_price": salePrice,
"donation_amt": donationAmt,
};
}
creating the model class for the json
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sample_testing_project/models.dart';
main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _currentSelectedValue;
List<Datum> data = List();
bool _isLoading = false;
String selectedUser;
#override
void initState() {
// TODO: implement initState
super.initState();
loadYourData();
}
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
loadYourData() async {
setState(() {
_isLoading = true;
});
// Loading your json locally you can make an api call, when you get the response just pass it to the productListFromJson method
String jsonString = await loadFromAssets();
final productList = productListFromJson(jsonString);
data = productList.data;
setState(() {
_isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: _isLoading
? Text('Loading')
: Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(25.0, 20.0, 0, 0),
child: Container(
width: 160,
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
border: Border.all(
color: Colors.red,
style: BorderStyle.solid,
width: 0.80),
),
child: DropdownButton(
value: selectedUser,
isExpanded: true,
icon: Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Icon(Icons.arrow_drop_down),
),
iconSize: 25,
underline: SizedBox(),
onChanged: (newValue) {
setState(() {
selectedUser = newValue;
});
},
hint: Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Select'),
),
items: data.map((data) {
return DropdownMenuItem(
value: data.id,
child: Padding(
padding: const EdgeInsets.only(left: 10.0),
child: Text(
data.id + ':' + data.productName,
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
);
}).toList()),
),
),
),
),
);
}
}
check out the changes that i have made using your same ui.
Let me know if its working.
Thanks.
Remember: "JSON is not 'nested.'" When you're given a JSON string, you decode it and this gives you a data-structure ... which very well might be "nested." How to handle that correctly is up to you.
Always treat JSON (or YAML, or XML) as a "black box." Use the utilities provided in the language to encode, decode and parse them.