I need some help in flutter data mapping. I have a JSON object that is returning some fields. I have to create a form depending on those fields. The issue that I am facing right now is that I cannot map the JSON dictionary to my dropdown list.
So basically I want to create a dropdown options that are in form_field_options of my json.
Here is a code sample of what I am trying to active, JSON return by my server is:
{
"status": "200",
"request": "0",
"message": "Success",
"data": {
"assetID": "155",
"assetTitle": "TPO",
"formTitle": "Roof Asset",
"preFields": [
{
"unique_id": "uid_201955451258",
"form_name": "General Overview",
"form_field_type": "100",
"form_field_required": "0",
"form_field_private": "0",
"form_field_duplicate_times": "00",
"form_field_disabledrow": "0"
},
{
"unique_id": "uid_201939764918",
"form_name": "Asset ID",
"form_field_type": "5",
"form_field_required": "1",
"form_field_private": "0",
"form_field_duplicate_times": "00",
"form_field_disabledrow": "0"
},
{
"unique_id": "uid_201789014253",
"form_name": "Facility ID",
"form_field_type": "5",
"form_field_required": "0",
"form_field_private": "0",
"form_field_duplicate_times": "00",
"form_field_disabledrow": "0"
},
{
"unique_id": "uid_201996716360",
"form_name": "Location",
"form_field_type": "19",
"form_field_required": "0",
"form_field_private": "0",
"form_field_duplicate_times": "00",
"form_field_disabledrow": "0"
},
{
"unique_id": "uid_201941758250",
"form_name": "Developed Area Type",
"form_field_type": "1",
"form_field_required": "0",
"form_field_private": "0",
"form_field_duplicate_times": "00",
"form_field_options": {
"1": {
"opt_name": "Suburban",
"opt_weightage": ""
},
"2": {
"opt_name": "Urban",
"opt_weightage": ""
},
"3": {
"opt_name": "Rural",
"opt_weightage": ""
}
},
"form_field_disabledrow": "0"
}
]
}
}
And here is my form class (auto generate class form quicktype) is:
// To parse this JSON data, do
//
// final form = formFromJson(jsonString);
import 'dart:convert';
Form formFromJson(String str) => Form.fromJson(json.decode(str));
String formToJson(Form data) => json.encode(data.toJson());
class Form {
String status;
String request;
String message;
Data data;
Form({
this.status,
this.request,
this.message,
this.data,
});
factory Form.fromJson(Map<String, dynamic> json) => new Form(
status: json["status"],
request: json["request"],
message: json["message"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"request": request,
"message": message,
"data": data.toJson(),
};
}
class Data {
String assetId;
String assetTitle;
String formTitle;
List<PreField> preFields;
Data({
this.assetId,
this.assetTitle,
this.formTitle,
this.preFields,
});
factory Data.fromJson(Map<String, dynamic> json) => new Data(
assetId: json["assetID"],
assetTitle: json["assetTitle"],
formTitle: json["formTitle"],
preFields: new List<PreField>.from(json["preFields"].map((x) => PreField.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"assetID": assetId,
"assetTitle": assetTitle,
"formTitle": formTitle,
"preFields": new List<dynamic>.from(preFields.map((x) => x.toJson())),
};
}
class PreField {
String uniqueId;
String formName;
String formFieldType;
String formFieldRequired;
String formFieldPrivate;
String formFieldDuplicateTimes;
String formFieldDisabledrow;
Map<String, FormFieldOption> formFieldOptions;
PreField({
this.uniqueId,
this.formName,
this.formFieldType,
this.formFieldRequired,
this.formFieldPrivate,
this.formFieldDuplicateTimes,
this.formFieldDisabledrow,
this.formFieldOptions,
});
factory PreField.fromJson(Map<String, dynamic> json) => new PreField(
uniqueId: json["unique_id"],
formName: json["form_name"],
formFieldType: json["form_field_type"],
formFieldRequired: json["form_field_required"],
formFieldPrivate: json["form_field_private"],
formFieldDuplicateTimes: json["form_field_duplicate_times"],
formFieldDisabledrow: json["form_field_disabledrow"],
formFieldOptions: json["form_field_options"] == null ? null : new Map.from(json["form_field_options"]).map((k, v) => new MapEntry<String, FormFieldOption>(k, FormFieldOption.fromJson(v))),
);
Map<String, dynamic> toJson() => {
"unique_id": uniqueId,
"form_name": formName,
"form_field_type": formFieldType,
"form_field_required": formFieldRequired,
"form_field_private": formFieldPrivate,
"form_field_duplicate_times": formFieldDuplicateTimes,
"form_field_disabledrow": formFieldDisabledrow,
"form_field_options": formFieldOptions == null ? null : new Map.from(formFieldOptions).map((k, v) => new MapEntry<String, dynamic>(k, v.toJson())),
};
}
class FormFieldOption {
String optName;
String optWeightage;
FormFieldOption({
this.optName,
this.optWeightage,
});
factory FormFieldOption.fromJson(Map<String, dynamic> json) => new FormFieldOption(
optName: json["opt_name"],
optWeightage: json["opt_weightage"],
);
Map<String, dynamic> toJson() => {
"opt_name": optName,
"opt_weightage": optWeightage,
};
}
Now when I try to apply loop or mapping on my options list (Which runs perfectly if its list) like this, It will not map it:
Column(
children: <Widget>[
FormBuilderDropdown(
attribute: item.uniqueId,
decoration:
InputDecoration(labelText: item.formName),
// initialValue: 'Male',
hint: Text(item.formName),
// validators: [
// FormBuilderValidators.required()
// ],
items: item.formFieldOptions.map((option) => DropdownMenuItem(
value: option,
child: Text("$option.optName")))
.toList(),
),
],
),
It throws me error that:
> The argument type '(String) → MapEntry<?, ?>' can't be assigned to the
> parameter type '(String, FormFieldOption) → MapEntry<dynamic,
> dynamic>'.dart(argument_type_not_assignable)
Please help or let me know what am I doing wrong. How can I make those dropdown options.
Thanks in advance
You sould try to map with the correct lambda signature (k, v) =>
items: item.formFieldOptions.map((key, option) => DropdownMenuItem(
value: key,
child: Text("${option.optName}"),
)
).toList()
Related
I have try to put my JSON data in flutter Stacked Chart.
I already work on simple charts using JSON Data like bar, column, pie, Doughnut charts etc.
I have refer
stacked-column-chart(syncfusion_flutter_charts),
Grouped Bar Chart(charts_flutter)
Stack Overflow Que-Ans
below like my API response/JSON String
[{
"name": "ABC",
"subject": [{
"name": "Math",
"marks": "54"
},
{
"name": "Physics",
"marks": "65"
}
]
},
{
"name": "PQR",
"subject": [{
"name": "Chemistry",
"marks": "53"
},
{
"name": "Biology",
"marks": "22"
},
{
"name": "English",
"marks": "7 "
},
{
"name": "Math",
"marks": "12"
}
]
}, {
"name": "JKL",
"subject": [{
"name": "Chemistry",
"marks": "53"
},
{
"name": "Biology",
"marks": "22"
},
{
"name": "English",
"marks": "79 "
},
{
"name": "Math",
"marks": "12"
},
{
"name": "Physics",
"marks": "72"
}
]
}
]
Or I want below type of graph using JSON Data
Note: Suggest me my JSON string is wrong, you can create your own JSON data and display the output
Using charts_flutter. Please customize it for your usecase its a bare minimum implementation to validate that its working for your json.
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'dart:convert';
class StackedBarChart extends StatelessWidget {
final bool animate;
StackedBarChart({this.animate = false});
// EXCLUDE_FROM_GALLERY_DOCS_END
#override
Widget build(BuildContext context) {
String jsonString = '[{"name":"ABC","subject":[{"name":"Math","marks":"54"},{"name":"Physics","marks":"65"}]},{"name":"PQR","subject":[{"name":"Chemistry","marks":"53"},{"name":"Biology","marks":"22"},{"name":"English","marks":"7 "},{"name":"Math","marks":"12"}]},{"name":"JKL","subject":[{"name":"Chemistry","marks":"53"},{"name":"Biology","marks":"22"},{"name":"English","marks":"79 "},{"name":"Math","marks":"12"},{"name":"Physics","marks":"72"}]}]';
final studentMarks = studentMarksFromJson(jsonString);
var subjects = <Subject?>{};
var subjectsDist = <Subject?>{};
int c=0;
for (var stdnt in studentMarks) {
for (var subjs in stdnt.subject) {
if (!subjectsDist.where((element) => element?.name==subjs.name).isNotEmpty) {
subjs.sno=c++;
subjectsDist.add(subjs);
}
}
}
print(subjectsDist.length);
List<List<OrdinalMarks>> SubjectData = [];
for (var subjs in subjectsDist) {
List<OrdinalMarks> marksData = [];
for (var stdnt in studentMarks) {
if (stdnt.subject
.where((element) => element.name == subjs?.name).isNotEmpty) {
var temp = stdnt.subject
.where((element) => element.name == subjs?.name)
.first;
marksData.add(OrdinalMarks(temp.name, int.parse(temp.marks),stdnt.name));
} else {
marksData.add(OrdinalMarks(subjs!.name, 0,stdnt.name));
}
}
SubjectData.add(marksData);
}
var palettes = charts.MaterialPalette.getOrderedPalettes(subjectsDist.length+2);
int cnt=0;
List<charts.Series<OrdinalMarks, String>> chartData = [
];
for(var d in SubjectData)
{
chartData.add(new charts.Series<OrdinalMarks, String>(
id: d.first.subjectName,
domainFn: (OrdinalMarks m, _) => m.studentName,
measureFn: (OrdinalMarks m, _) => m.marks,
data: d,
fillColorFn: ( subj, _) {
// print(subj.subjectName+": subj.subjectName :" + pallets[subj.subjectName].toString()??charts.MaterialPalette.blue.shadeDefault.toString());
return palettes.elementAt( subjectsDist.where((element) => element?.name==subj.subjectName).first?.sno??0 ).shadeDefault; //pallets[subj.subjectName]??charts.MaterialPalette.blue.shadeDefault;
},
colorFn: ( subj, _) {
// print(subj.subjectName+": subj.subjectName :" + pallets[subj.subjectName].toString()??charts.MaterialPalette.blue.shadeDefault.toString());
return palettes.elementAt(subjectsDist.where((element) => element?.name==subj.subjectName).first?.sno??0).shadeDefault;
},
));
}
return Scaffold(
// Use Obx(()=> to update Text() whenever count is changed.
appBar: AppBar(title: Text("Chart")),
// Replace the 8 lines Navigator.push by a simple Get.to(). You don't need context
body:new charts.BarChart(
chartData,
animate: animate,
behaviors: [new charts.SeriesLegend(showMeasures: true)],
animationDuration: Duration(seconds: 3),
));
}
}
/// Sample ordinal data type.
class OrdinalMarks {
final String subjectName;
final int marks;
final String studentName;
OrdinalMarks(this.subjectName, this.marks,this.studentName);
}
List<StudentMarks> studentMarksFromJson(String str) => List<StudentMarks>.from(json.decode(str).map((x) => StudentMarks.fromJson(x)));
String studentMarksToJson(List<StudentMarks> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class StudentMarks {
StudentMarks({
required this.name,
required this.subject,
});
String name;
List<Subject> subject;
factory StudentMarks.fromJson(Map<String, dynamic> json) => StudentMarks(
name: json["name"],
subject: List<Subject>.from(json["subject"].map((x) => Subject.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"name": name,
"subject": List<dynamic>.from(subject.map((x) => x.toJson())),
};
}
class Subject {
Subject({
required this.name,
required this.marks,
});
String name;
String marks;
int? sno;
factory Subject.fromJson(Map<String, dynamic> json) => Subject(
name: json["name"],
marks: json["marks"],
);
Map<String, dynamic> toJson() => {
"name": name,
"marks": marks,
};
}
HERE IS THE JSON OF RESPONSE BODY:
{
"status": "success",
"contents": [{
"id": "15",
"cname": "DOGS",
"dogs_image": "1638695967-rtyyyt.jpg",
"cat_image": "1638695967-jhjjj.jpg",
"sub_category": [{
"subcatid": "36",
"cat_id": "15",
"sub_category_name": "Accessories",
"banner": null,
"image": "1638695982-ACCESORIE.jpg"
}, {
"subcatid": "39",
"cat_id": "15",
"sub_category_name": "Beds",
"banner": null,
"image": "1638695982-ACCESORIE.jpg"
}]
}, {
"id": "14",
"cname": "CATS",
"dogs_image": "1638695967-rtyyyt.jpg",
"cat_image": "1638695967-jhjjj.jpg",
"sub_category": [{
"subcatid": "47",
"cat_id": "14",
"sub_category_name": "Accessories",
"banner": null,
"image": "1638695982-ACCESORIE.jpg"
}]
}]
}
// API call to get the above json data:
Future<List<CatListData>> dashboardDataAPI(http.Client client) async {
final response = await client.get(Uri.parse(Utilities.BASE_URL));
List list = json.decode(response.body)['contents'];
return parsePhotos(list.toString());
}
// A function that converts a response body into a List
List<CatListData> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<CatListData>((json) => CatListData.fromJson(json)).toList();
}
// Cat List Class
class CatListData{
final String id;
final String cName;
final String dogImage;
final String catImage;
final List<SubCatListData> subCatListDataList;
CatListData({required this.id, required this.cName, required this.dogImage, required this.catImage, required this.subCatListDataList});
factory CatListData.fromJson(Map<String, dynamic> json) {
return CatListData(
id: json['id'] as String,
cName: json['cname'] as String,
dogImage: json['dogs_image'] as String,
catImage: json['cat_image'] as String,
subCatListDataList: List<SubCatListData>.from(json['sub_category'] as Iterable),
);
}
}
// Sub Cat Class
class SubCatListData{
final String subCatId;
final String catId;
final String subCategoryName;
final String banner;
final String image;
SubCatListData({required this.subCatId, required this.catId, required this.subCategoryName, required this.banner, required this.image});
factory SubCatListData.fromJson(Map<String, dynamic> json) {
return SubCatListData(
subCatId: json['subcatid'] as String,
catId: json['cat_id'] as String,
subCategoryName: json['sub_category_name'] as String,
banner: json['banner'] as String,
image: json['image'] as String,
);
}
}
Here showing null when I print snapshot
Container(
child: FutureBuilder<List<CatListData>>(
future: dashboardDataAPI(http.Client()),
builder: (context, snapshot) {
print("Response:: "+snapshot.data.toString());
if (snapshot.hasData) {
return PhotosList(photos: snapshot.data!);
}else if(snapshot.hasError){
return const Center(
child: Text('An error has occurred!'),);
}else{
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
)
Please let me know how I can fix this issue and parse the multiple json array data into the list.
Thanks
I believe the problem happens on this line on the CatListData.fromJson constructor:
subCatListDataList: List<SubCatListData>.from(json['sub_category'] as Iterable),
you never call SubCatListData.fromJson, I believe this will work better for your assignment:
subCatListDataList: (json['sub_category'] as Iterable).map<SubCatListData>(
(value) => SubCatListData.fromJson(value as Map<String, dynamic>),
),
I need a quick help for the syntax to display JSON data which are in array list format(I guess)
I'm able to display Status & Message but struggling with syntax when I want to display Name Image which are inside Data[]. What syntax I should use to display those data ?
My JSON response
{
"Status": "1",
"Message": "3 records found.",
"Data": [
{
"Name": "Brain surgery",
"EncId": "B909+U0FIAHIs+sl3IYTvQ==",
"Image": "",
"Extra1": "abdsjh dsgjhgdd gsjjkdkds dddsjkhdj djdjkdh dshjdkhkd dhdhdk sjkghdjkdhkhd dhkdkhdkjhd hkjhkdhd kdjkdjdkjd dhkdkjhdjh ddkdkhd dhdhhd . dgjgdjd dgdgjds",
"Extra2": "",
"ResultFor": "p6r4bAAI4ybdJySoV+PqGQ=="
},
{
"Name": "Dr Ram Das",
"EncId": "fXVmzecGStqrhx1PmIgwlQ==",
"Image": "http://medbo.digitalicon.in/Doctor/U7MK2MZGD0QVQ7E8IR7N.jpg",
"Extra1": "ENT",
"Extra2": "kj",
"ResultFor": "xPCleDOirQpArdOv0uUR9g=="
},
{
"Name": "Kidney Routine Test with Sonography and Serology.",
"EncId": "U4exk+vfMGrn7cjNUa/PBw==",
"Image": "",
"Extra1": "",
"Extra2": "",
"ResultFor": "aZsjjLg3WIBbTg05/15o2w=="
}
]
}
My model class
class SearchApiResponse {
SearchApiResponse({
required this.status,
required this.message,
required this.data,
});
String status;
String message;
List<SearchData> data;
factory SearchApiResponse.fromJson(Map<String, dynamic> json) => SearchApiResponse(
status: json["Status"],
message: json["Message"],
data: List<SearchData>.from(json["Data"].map((x) => SearchData.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Status": status,
"Message": message,
"Data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class SearchData {
SearchData({
required this.name,
required this.encId,
required this.image,
required this.extra1,
required this.extra2,
required this.resultFor,
});
String name;
String encId;
String image;
String extra1;
String extra2;
String resultFor;
factory SearchData.fromJson(Map<String, dynamic> json) => SearchData(
name: json["Name"],
encId: json["EncId"],
image: json["Image"],
extra1: json["Extra1"],
extra2: json["Extra2"],
resultFor: json["ResultFor"],
);
Map<String, dynamic> toJson() => {
"Name": name,
"EncId": encId,
"Image": image,
"Extra1": extra1,
"Extra2": extra2,
"ResultFor": resultFor,
};
}
And Here I can successfully display Status & the message but how to display others which are inside Data[] ?
class AfterSearchPage extends StatefulWidget {
final SearchApiResponse rresponse;
const AfterSearchPage({required this.rresponse});
#override
_AfterSearchPageState createState() => _AfterSearchPageState();
}
class _AfterSearchPageState extends State<AfterSearchPage> {
var responseRef;
// _SecondState(this.responseRef);
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Status: ${widget.rresponse.status}"),
Text("Message: ${widget.rresponse.message}"),
Text("Name: ${widget.rresponse.data.name}"),//==??????????????????????????????????????Error
SizedBox(
height: 50,
),
OutlinedButton.icon(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Home2(),
),
);
},
icon: Icon(
Icons.exit_to_app,
size: 18,
),
label: Text("GoTo Home")),
],
),
),
),
);
}
}
Data is an array, so you need to address it as such.
for (var d in folder.data) {
print(d.name);
}
Here's a sample project to show you that:
import 'dart:convert';
void main() {
final folder = Folder.fromJson(json.decode('''{
"Status": "1",
"Message": "3 records found.",
"Data": [
{
"Name": "Brain surgery",
"EncId": "B909+U0FIAHIs+sl3IYTvQ==",
"Image": "",
"Extra1": "abdsjh dsgjhgdd gsjjkdkds dddsjkhdj djdjkdh dshjdkhkd dhdhdk sjkghdjkdhkhd dhkdkhdkjhd hkjhkdhd kdjkdjdkjd dhkdkjhdjh ddkdkhd dhdhhd . dgjgdjd dgdgjds",
"Extra2": "",
"ResultFor": "p6r4bAAI4ybdJySoV+PqGQ=="
},
{
"Name": "Dr Ram Das",
"EncId": "fXVmzecGStqrhx1PmIgwlQ==",
"Image": "http://medbo.digitalicon.in/Doctor/U7MK2MZGD0QVQ7E8IR7N.jpg",
"Extra1": "ENT",
"Extra2": "kj",
"ResultFor": "xPCleDOirQpArdOv0uUR9g=="
},
{
"Name": "Kidney Routine Test with Sonography and Serology.",
"EncId": "U4exk+vfMGrn7cjNUa/PBw==",
"Image": "",
"Extra1": "",
"Extra2": "",
"ResultFor": "aZsjjLg3WIBbTg05/15o2w=="
}
]
}'''));
print(folder.status);
print(folder.message);
for (var d in folder.data) {
print(d.name);
}
}
class Folder {
Folder({
this.status,
this.message,
this.data,
});
String status;
String message;
List<Data> data;
factory Folder.fromJson(Map<String, dynamic> json) => Folder(
status: json["Status"],
message: json["Message"],
data: List<Data>.from(json["Data"].map((x) => Data.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Status": status,
"Message": message,
"Data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Data {
Data({
this.name,
this.encId,
this.image,
this.extra1,
this.extra2,
this.resultFor,
});
String name;
String encId;
String image;
String extra1;
String extra2;
String resultFor;
factory Data.fromJson(Map<String, dynamic> json) => Data(
name: json["Name"],
encId: json["EncId"],
image: json["Image"],
extra1: json["Extra1"],
extra2: json["Extra2"],
resultFor: json["ResultFor"],
);
Map<String, dynamic> toJson() => {
"Name": name,
"EncId": encId,
"Image": image,
"Extra1": extra1,
"Extra2": extra2,
"ResultFor": resultFor,
};
}
You can test this code in dartpad: https://dartpad.dartlang.org
just give the index number
Text("Name: ${widget.rresponse.data[0].name}")
I am a beginner in Flutter. I was trying to extract data from api. I got response like this
"status": "success",
"data": {
"integration": "051st93cqk90gqeyuikkkii1s5il5d3p",
"rootcategory": 2,
"slider": [
{
"image": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b787d5beb55.png",
"type": "category",
"id": "6",
"sort_order": "0.00"
},
{
"image": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b787fb306c7.png",
"type": "product",
"id": "5",
"sort_order": "1.00"
}
],
"noimg": "https://omanphone.smsoman.com/api/media/omanphone_icon.png",
"catimages": [
{
"id": "6",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60b4857e526dd.jpg"
},
{
"id": "7",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d4142c0b.jpeg"
},
{
"id": "8",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d6440439.jpeg"
},
{
"id": "11",
"img": "https://omanphone.smsoman.com/mobile-admin/uploads/image_60ba1d7c6974c.jpeg"
}
],
"store_id": 1,
"minimum_order_amount": null,
"stores": [
],
"currency": "OMR",
"payment_imgs": [
"https://omanphone.smsoman.com/api/media/payment_all.png",
"https://omanphone.smsoman.com/api/media/cards.png"
],
"voucher_cat": 151,
"whatsapp": "96812345678",
"celebrity_id": 0,
"register_otp": "0",
"mobile_formats": [
{
"webiste": "base",
"len": 8,
"country_code": "+968",
"country": "OM",
"id": 1
}
],
"cmspages": {
"faq": 73,
"about": 72,
"terms": 71,
"privacy": 70
},
"pay_method_imgs": [
"https://omanphone.smsoman.com/pub/media/itoons/payment-icon.png",
"https://omanphone.smsoman.com/pub/media/itoons/cod-icon.png"
]
}
}
Using app.quicktype.io - I converted this data to model.
like below.
// To parse this JSON data, do
//
// final slideData = slideDataFromJson(jsonString);
import 'dart:convert';
SlideData slideDataFromJson(String str) => SlideData.fromJson(json.decode(str));
String slideDataToJson(SlideData data) => json.encode(data.toJson());
class SlideData {
SlideData({
this.status,
this.data,
});
String status;
Data data;
factory SlideData.fromJson(Map<String, dynamic> json) => SlideData(
status: json["status"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"data": data.toJson(),
};
}
class Data {
Data({
this.integration,
this.rootcategory,
this.slider,
this.noimg,
this.catimages,
this.storeId,
this.minimumOrderAmount,
this.stores,
this.currency,
this.paymentImgs,
this.voucherCat,
this.whatsapp,
this.celebrityId,
this.registerOtp,
this.mobileFormats,
this.cmspages,
this.payMethodImgs,
});
String integration;
int rootcategory;
List<Slider> slider;
String noimg;
List<Catimage> catimages;
int storeId;
dynamic minimumOrderAmount;
List<dynamic> stores;
String currency;
List<String> paymentImgs;
int voucherCat;
String whatsapp;
int celebrityId;
String registerOtp;
List<MobileFormat> mobileFormats;
Cmspages cmspages;
List<String> payMethodImgs;
factory Data.fromJson(Map<String, dynamic> json) => Data(
integration: json["integration"],
rootcategory: json["rootcategory"],
slider: List<Slider>.from(json["slider"].map((x) => Slider.fromJson(x))),
noimg: json["noimg"],
catimages: List<Catimage>.from(json["catimages"].map((x) => Catimage.fromJson(x))),
storeId: json["store_id"],
minimumOrderAmount: json["minimum_order_amount"],
stores: List<dynamic>.from(json["stores"].map((x) => x)),
currency: json["currency"],
paymentImgs: List<String>.from(json["payment_imgs"].map((x) => x)),
voucherCat: json["voucher_cat"],
whatsapp: json["whatsapp"],
celebrityId: json["celebrity_id"],
registerOtp: json["register_otp"],
mobileFormats: List<MobileFormat>.from(json["mobile_formats"].map((x) => MobileFormat.fromJson(x))),
cmspages: Cmspages.fromJson(json["cmspages"]),
payMethodImgs: List<String>.from(json["pay_method_imgs"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"integration": integration,
"rootcategory": rootcategory,
"slider": List<dynamic>.from(slider.map((x) => x.toJson())),
"noimg": noimg,
"catimages": List<dynamic>.from(catimages.map((x) => x.toJson())),
"store_id": storeId,
"minimum_order_amount": minimumOrderAmount,
"stores": List<dynamic>.from(stores.map((x) => x)),
"currency": currency,
"payment_imgs": List<dynamic>.from(paymentImgs.map((x) => x)),
"voucher_cat": voucherCat,
"whatsapp": whatsapp,
"celebrity_id": celebrityId,
"register_otp": registerOtp,
"mobile_formats": List<dynamic>.from(mobileFormats.map((x) => x.toJson())),
"cmspages": cmspages.toJson(),
"pay_method_imgs": List<dynamic>.from(payMethodImgs.map((x) => x)),
};
}
class Catimage {
Catimage({
this.id,
this.img,
});
String id;
String img;
factory Catimage.fromJson(Map<String, dynamic> json) => Catimage(
id: json["id"],
img: json["img"],
);
Map<String, dynamic> toJson() => {
"id": id,
"img": img,
};
}
class Cmspages {
Cmspages({
this.faq,
this.about,
this.terms,
this.privacy,
});
int faq;
int about;
int terms;
int privacy;
factory Cmspages.fromJson(Map<String, dynamic> json) => Cmspages(
faq: json["faq"],
about: json["about"],
terms: json["terms"],
privacy: json["privacy"],
);
Map<String, dynamic> toJson() => {
"faq": faq,
"about": about,
"terms": terms,
"privacy": privacy,
};
}
class MobileFormat {
MobileFormat({
this.webiste,
this.len,
this.countryCode,
this.country,
this.id,
});
String webiste;
int len;
String countryCode;
String country;
int id;
factory MobileFormat.fromJson(Map<String, dynamic> json) => MobileFormat(
webiste: json["webiste"],
len: json["len"],
countryCode: json["country_code"],
country: json["country"],
id: json["id"],
);
Map<String, dynamic> toJson() => {
"webiste": webiste,
"len": len,
"country_code": countryCode,
"country": country,
"id": id,
};
}
class Slider {
Slider({
this.image,
this.type,
this.id,
this.sortOrder,
});
String image;
String type;
String id;
String sortOrder;
factory Slider.fromJson(Map<String, dynamic> json) => Slider(
image: json["image"],
type: json["type"],
id: json["id"],
sortOrder: json["sort_order"],
);
Map<String, dynamic> toJson() => {
"image": image,
"type": type,
"id": id,
"sort_order": sortOrder,
};
}
Future<void> getDataFromInternet() async {
//getting data from Internet
try {
var response =
await http.get('https://omanphone.smsoman.com/api/configuration');
} catch (error) {
print(error);
}
}
I just want to get slider images. So What did I need to do in above code?
I used http package and var response =
await http.get('https://omanphone.smsoman.com/api/configuration'); did this. But I don't know how to extract it.
I am not able to parse below mentioned json data in flutter.
[
{
"id": 96,
"name": "Entertainment",
"link": "https://thehappilyeverafter.in/listing-category/entertainment/",
"image": "https://thehappilyeverafter.in/wp-content/uploads/2021/05/a685b39b20592b03c0939878edb0cb84.jpg",
"children": [
{
"child_id": 114,
"child_name": "DJs",
"child_link": "https://thehappilyeverafter.in/listing-category/djs/"
},
{
"child_id": 117,
"child_name": "Live Music",
"child_link": "https://thehappilyeverafter.in/listing-category/live-music/"
},
{
"child_id": 115,
"child_name": "Wedding Choreographer",
"child_link": "https://thehappilyeverafter.in/listing-category/wedding-choreographer/"
},
{
"child_id": 116,
"child_name": "Wedding Entertainment",
"child_link": "https://thehappilyeverafter.in/listing-category/wedding-entertainment/"
}
]
}
]`
import 'dart:convert';
List<Root> rootFromJson(String str) => List<Root>.from(json.decode(str).map((x) => Root.fromJson(x)));
String rootToJson(List<Root> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Root {
Root({
this.id,
this.name,
this.link,
this.image,
this.children,
});
int id;
String name;
String link;
String image;
List<Children> children;
factory Root.fromJson(Map<String, dynamic> json) => Root(
id: json["id"],
name: json["name"],
link: json["link"],
image: json["image"] == null ? null : json["image"],
children: List<Children>.from(json["children"].map((x) => Children.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"link": link,
"image": image == null ? null : image,
"children": List<dynamic>.from(children.map((x) => x.toJson())),
};
}
class Children {
Children({
this.childId,
this.childName,
this.childLink,
});
int childId;
String childName;
String childLink;
factory Children.fromJson(Map<String, dynamic> json) => Children(
childId: json["child_id"],
childName: json["child_name"],
childLink: json["child_link"],
);
Map<String, dynamic> toJson() => {
"child_id": childId,
"child_name": childName,
"child_link": childLink,
};
}
[Getting this error][1]
`
type 'List' is not a subtype of type 'Children'
Since your json is a list, you should loop through it:
final List<Root> roots = yourJson.map((element) {
return Root.fromJson(element);
}).toList();
print(roots.first.image);
//https://thehappilyeverafter.in/wp-content/uploads/2021/05/a685b39b20592b03c0939878edb0cb84.jpg