If my API needs to accept this type of data
{
"name": "myName",
"email": "myEmail,
"phone": "0323456789",
"info": "myDescription",
"social_media": [
{
"link":"First link"
"social_media_id": 1
}
{
"link":"First link"
"social_media_id": 1
}
{
"link":"First link"
"social_media_id": 1
}
]
}
then I am sending that data using following code in my method, but the response I am getting is(Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>')
for(int i=0;i<3;i++)
{
_socialList.add(
{
"link":_controllers[i].text,
"social_media_id": 1,
},);
}
Map<String, dynamic> data={
"name":userNameController.text,
"email":emailController.text,
"phone":phoneController.text,
"info": detailsController.text,
"social_media": _socialList
};
var stream= new http.ByteStream(image.openRead());
stream.cast();
var length= await image.length();
var request= new http.MultipartRequest('POST', url);
request.fields.addAll(data);
var multiPort= new http.MultipartFile('file', stream, length,
filename: image.path);
request.files.add(multiPort);
var response=await request.send();
you can do this way also:
var mainObj ={};
var socialMedia = [];
mainObj["name"] = "myName";
mainObj["email"] = "myEmail";
mainObj["phone"] = "0323456789";
mainObj["info"] = "myDescription";
for(int j=0;j<3; j++){
var innerObj ={};
innerObj["link"] = "$j link";
innerObj["social_media_id"] = j;
socialMedia.add(innerObj);
}
mainObj["social_media"] = socialMedia;
print(jsonEncode(mainObj));
Just pass this jsonEncode(mainObj) to the body of http.post method
EDIT
var socialMedia = [];
for(int j=0;j<3; j++){
var innerObj ={};
innerObj["link"] = "$j link";
innerObj["social_media_id"] = j;
socialMedia.add(innerObj);
}
Map<String, String> data = {
"name" : "myName",
"email" : "myEmail",
"phone" : "0323456789",
"info" : "myDescription",
"social_media" : socialMedia.toString()
} ;
var request = new MultipartRequest("POST", Uri.parse('apiUrl'));
request.fields.addAll(data);
request.send().then((response) {
if (response.statusCode == 200) print("done!");
});
Step 1:
Future<List<=UserData>> fetchResults() async {
List< UserData> _results = [];
var url ="---your link----";
var response = await http.get(url);
if (response.statusCode == 200) {
var resultsJson = json.decode(response.body).cast<Map<String,dynamic>>();
await Future.forEach(resultsJson, (element) {
_results.add(UserData.fromJson(element));
});
}
return Future.value(_results);
}
Step 2:
class UserData {
String? name;
String? email;
String? phone;
String? info;
List<SocialMedia>? socialMedia;
UserData({this.name, this.email, this.phone, this.info, this.socialMedia});
UserData.fromJson(Map<String, dynamic> json) {
name = json['name'];
email = json['email'];
phone = json['phone'];
info = json['info'];
if (json['social_media'] != null) {
socialMedia = <SocialMedia>[];
json['social_media'].forEach((v) {
socialMedia!.add(new SocialMedia.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['email'] = this.email;
data['phone'] = this.phone;
data['info'] = this.info;
if (this.socialMedia != null) {
data['social_media'] = this.socialMedia!.map((v) => v.toJson()).toList();
}
return data;
}
}
class SocialMedia {
String? link;
int? socialMediaId;
SocialMedia({this.link, this.socialMediaId});
SocialMedia.fromJson(Map<String, dynamic> json) {
link = json['link'];
socialMediaId = json['social_media_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['link'] = this.link;
data['social_media_id'] = this.socialMediaId;
return data;
}
}
Related
I am facing issue in sending the below data as a patch request.
The issue I am facing is I am not able to pass the Detail object data within another object(AddPerson) hence if you could please help me resolve this issue.
Additionally the data is being captured correctly but the format of the data as shown in sample data is not being captured.
Hence if you could please help in resolving this issue.
Below is the code
Model.dart
class AddPerson {
String? personId;
String? personName;
List<Details>? details;
AddPerson(
{this.personId, this.personName, this.details});
AddPerson.fromJson(Map<String, dynamic> json) {
personId = json['personId'];
personName = json['personName'];
if (json['details'] != null) {
details = <Details>[];
json['details'].forEach((v) {
details!.add(new Details.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['personId'] = this.personId;
data['personName'] = this.personName;
if (this.details != null) {
data['details'] = this.details!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Details with ChangeNotifier {
String? type;
String? price;
String? notificationId;
Details({this.type, this.price, this.notificationId});
Details.fromJson(Map<String, dynamic> json) {
type = json['type'];
price = json['price'];
notificationId = json['notification_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['type'] = this.type;
data['price'] = this.price;
data['notification_id'] = this.notificationId;
return data;
}
}
Provider.dart
Future<void> updateAddPerson(
List<AddPerson> newNotification, List<Details> s) async {
Map<String, String> headers = {
// "Content-Type": "charset=utf-8",
"Content-type": "application/json"
};
var uri = Uri.parse('http://localhost:3001/users/update/person');
try {
var request = http.MultipartRequest('PATCH', uri);
request.headers.addAll(headers);
for (int i = 0; i <= newNotification.length - 1; i++) {
request.fields['personId[$i]'] = '${newNotification[i].personId}';
request.fields['personName[$i]'] = '${newNotification[i].personName}';
for (int m = 0; m <= s.length - 1; m++) {
request.fields['notification_id[$m]'] = '${s[m].notificationId}';
request.fields['type[$m]'] = '${s[m].type}';
request.fields['price[$m]'] = '${s[m].price}';
}
}
var response = await request.send();
print(response.statusCode);
if (response.statusCode == 201) {
notifyListeners();
} else {
print('invalid data ');
}
} catch (error) {
print('NA');
}
}
Sample result
[
{
"personId": "1",
"personName":"Akash”,
"details": [
{
"notification_id": 1,
"type": “SUV”,
"price": "200"
},
{
"notification_id": 2,
"type": “SUV”,
"price": "250"
}
]
}
]
When I try try to pull my Add_ons. it is prepared with data key of a UUID and values of List body. Essentially what I am asking is how I get the values (name, price and type) in add_ons. Structure at the end.
Here is the preparation of the data to be sent to API
Map<String, dynamic> extrasJsonPrepare() {
Map<String, dynamic> addOnBody = {};
if (extras.isNotEmpty) {
for (int i = 0; i < extras.length; i++) {
addOnBody["${uuid.v4()}"] = {
"name": "${extras[i].name}",
"price": extras[i].price,
"type": "extras"
};
}
}
...........
}
Trying to pull the data from the API code
import 'dart:convert';
import 'package:uuid/uuid.dart';
MealJSON mealFromJson(String str) => MealJSON.fromJson(json.decode(str));
String mealToJson(MealJSON data) => json.encode(data.toJson());
class MealJSON {
int code;
List<MealboxListing> data;
MealJSON({this.code, this.data});
MealJSON.fromJson(Map<String, dynamic> json) {
code = json['code'];
data = json['data'] != null
? (json['data'] as Iterable)
.map((data) => MealboxListing.fromJson(data))
.toList()
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['code'] = this.code;
if (this.data != null) {
data['data'] = this.data;
}
return data;
}
}
class MealboxListing {
List<AddOn> addOns;
bool availability;
double averageRating;
String cityLive;
String deliveryDate;
String description;
List<String> imageDetails;
String kitchenDetails;
String listingId;
int numberOfMeals;
String origin;
String title;
double price;
List<String> preferences;
List<String> tag;
List<String> included;
MealboxListing(
{this.addOns,
this.availability,
this.averageRating,
this.cityLive,
this.deliveryDate,
this.description,
this.imageDetails,
this.kitchenDetails,
this.listingId,
this.numberOfMeals,
this.origin,
this.title,
this.preferences,
this.tag,
this.included,
this.price});
MealboxListing.fromJson(Map<String, dynamic> json) {
// addOns = json['add_ons'] != null ? new AddOn.fromJson(json[addOns]) : null;
if (json['add_ons'] != null) {
addOns = new List<AddOn>();
json['add_ons'].forEach((v) {
addOns.add(new AddOn.fromJson(v));
});
}
availability = json['available'];
averageRating = json['average_rating'];
cityLive = json['city_live'];
deliveryDate = json['delivery_on'];
description = json['description'];
imageDetails = json['img_url'].cast<String>();
kitchenDetails = json['kitchen'];
listingId = json['listing_id'];
numberOfMeals = json['no_of_meals'];
origin = json['origin'];
title = json['title'];
price = json['price_before_sankara_charges'];
preferences = json['preferences'].cast<String>();
tag = json['tags'].cast<String>();
included = json['whats_included'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.addOns != null) {
data['add_ons'] = this.addOns.map((v) => v.toJson()).toList();
}
data['available'] = this.availability;
data['average_rating'] = this.averageRating;
data['city_live'] = this.cityLive;
data['delivery_on'] = this.deliveryDate;
data['description'] = this.description;
data['img_url'] = this.imageDetails;
data['kitchen'] = this.kitchenDetails;
data['listing_id'] = this.listingId;
data['no_of_meals'] = this.numberOfMeals;
data['origin'] = this.origin;
data['title'] = this.title;
data['preferences'] = this.preferences;
data['tags'] = this.tag;
data['whats_included'] = this.included;
data['price_before_sankara_charges'] = this.price;
return data;
}
}
class AddOn {
String name;
String type;
int price;
// List<uuid> = Uuid();
// var uuid = Uuid();
AddOn({
// this.uuid,
this.name,
this.price,
this.type,
});
AddOn.fromJson(Map<String, dynamic> json) {
// uuid = json['$uuid'];
name = json['name'];
price = json['price'];
type = json['type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
// data['$uuid'] = this.uuid;
data['name'] = this.name;
data['price'] = this.price;
data['type'] = this.type;
return data;
}
}
Structure of API
{
"add_ons": {
"681c3755-40a1-4711-9072-c848a2eaeea3": {
"name": "hgfhfgh",
"price": 9,
"type": "drinks"
},
"90e2bfe7-f81b-47c1-bb02-0fb227ddfff2": {
"name": "gdfgfdg",
"price": 9,
"type": "extras"
},
"b5c78d1c-9ce3-46ce-a168-6358259d4982": {
"name": "ghgfhgfh",
"price": 9,
"type": "sides"
}
},
"available": true,
"average_rating": 0.0,
"city_live": "Fredericton",
"delivery_on": "Tuesday",
"description": "dsadasds",
"img_url": [],
"kitchen": "sadasda",
"listing_id": "cd78ac9f-0f9c-49eb-8a52-970c2017fee9",
"no_of_meals": 1,
"origin": "Canada",
"preferences": [
"Gluten Free"
],
"price_before_sankara_charges": 6.0,
"tags": [],
"title": "dsadsad",
"whats_included": []
},
Fixed by adding these lines of code
var innerMap = json['add_ons'];
var targetMap = Map<String, AddOn>();
innerMap.forEach((key, value) {
targetMap.addAll({key: AddOn.fromJson(value)});
});
I am trying to build an e-commerce app using flutter and woocommece api.But when i try to press addtocart button this is what i get :
products:List (1 item)
userId:null
hashCode:383444147
runtimeType:Type (CartRequestModel)
i get products but i am not getting userId.
Here is my config.dart:
class Config {
static String key = "ck_xxxxxxxxxxxxxxxxxxxxxxxxxx";
static String secret = "cs_xxxxxxxxxxxxxxxxxxxx7dc9feb";
static String url = "https://gngbd.xyz/wp-json/wc/v3";
static String customerURL = "/customers";
static String tokenUR = "https://gngbd.xyz/wp-json/jwt-auth/v1/token";
static String categoryURL = "/products/categories";
static String productsURL = "/products";
static String todayOffersTagId = "20";
static String addToCartURL = "/addtocart";
static String cartURL = "/cart";
static String userId = "4";
}
Here is my cart_provider.dart :
import 'package:flutter/material.dart';
import 'package:grocerry/api_service.dart';
import 'package:grocerry/models/cart_request_model.dart';
import 'package:grocerry/models/cart_response_model.dart';
class CartProvider with ChangeNotifier {
ApiService apiService;
List<CartItem> _cartItems;
List<CartItem> get CartItems => _cartItems;
double get totalRecords => _cartItems.length.toDouble();
CartProvider() {
apiService = new ApiService();
// ignore: deprecated_member_use
_cartItems = new List<CartItem>();
}
void resetStreams() {
apiService = new ApiService();
// ignore: deprecated_member_use
_cartItems = new List<CartItem>();
}
void addToCart(CartProducts product, Function onCallBack) async {
CartRequestModel requestModel = new CartRequestModel();
// ignore: deprecated_member_use
requestModel.products = new List<CartProducts>();
if (_cartItems == null) resetStreams();
_cartItems.forEach((element) {
requestModel.products.add(new CartProducts(
productId: element.productId, quantity: element.qty));
});
var isProductExists = requestModel.products.firstWhere(
(prd) => prd.productId == product.productId,
orElse: () => null);
if (isProductExists != null) {
requestModel.products.remove(isProductExists);
}
requestModel.products.add(product);
await apiService.addToCart(requestModel).then((cartResponseModel) {
if (cartResponseModel.data != null) {
_cartItems = [];
_cartItems.addAll(cartResponseModel.data);
}
onCallBack(cartResponseModel);
notifyListeners();
});
}
}
Here i tried to build a addtocart function and also called the api_service.dart file
Here is my code for ApiService.dart :
Future<CartResponseModel> addToCart(CartRequestModel model) async {
model.userId = int.parse(Config.userId);
CartResponseModel responseModel;
try {
var response = await Dio().post(
Config.url + Config.addToCartURL,
data: model.toJson(),
options: new Options(
headers: {
HttpHeaders.contentTypeHeader: "application/json",
},
),
);
if (response.statusCode == 200) {
responseModel = CartResponseModel.fromJson(response.data);
}
} on DioError catch (e) {
// print(e.message);
if (e.response.statusCode == 404) {
print(e.response.statusCode);
} else {
print(e.message);
print(e.request);
}
}
return responseModel;
}
Future<CartResponseModel> getCartItems() async {
CartResponseModel responseModel;
try {
String url = Config.url +
Config.cartURL +
"?user_id=${Config.userId}&consumer_key=${Config.key}&consumer_secret=${Config.secret}";
print(url);
var response = await Dio().post(
url,
options: new Options(
headers: {
HttpHeaders.contentTypeHeader: "application/json",
},
),
);
if (response.statusCode == 200) {
responseModel = CartResponseModel.fromJson(response.data);
}
} on DioError catch (e) {
print(e.message);
}
return responseModel;
}
I have also two model one is for cart Request and another is for cartresponse model i am also providing this code
Here is my CartRequest.dart
class CartRequestModel {
int userId;
List<CartProducts> products;
CartRequestModel({this.userId, this.products});
CartRequestModel.fromJson(Map<String, dynamic> json) {
userId = json['user_id'];
if (json['products'] != null) {
// ignore: deprecated_member_use
products = new List<CartProducts>();
json['products'].forEach((v) {
products.add(new CartProducts.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['user_id'] = this.userId;
if (this.products != null) {
data['products'] = this.products.map((v) => v.toJson()).toList();
}
return data;
}
}
class CartProducts {
int productId;
int quantity;
CartProducts({this.productId, this.quantity});
CartProducts.fromJson(Map<String, dynamic> json) {
productId = json['product_id'];
quantity = json['quantity'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['product_id'] = this.productId;
data['quantity'] = this.quantity;
return data;
}
}
Here is my CartResponse Model and down below is my code please check if needed :
class CartResponseModel {
bool status;
List<CartItem> data;
CartResponseModel({this.status, this.data});
CartResponseModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
if (json['data'] != null) {
// ignore: deprecated_member_use
data = new List<CartItem>();
json['data'].forEach((v) {
data.add(new CartItem.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class CartItem {
int productId;
String productName;
String productRegularPrice;
String productsalePrice;
String thumbNail;
int qty;
double lineTotal;
double lineSubTotal;
CartItem(
{this.productId,
this.productName,
this.productRegularPrice,
this.productsalePrice,
this.thumbNail,
this.qty,
this.lineTotal,
this.lineSubTotal});
CartItem.fromJson(Map<String, dynamic> json) {
productId = json['product_id'];
productName = json['product_name'];
productRegularPrice = json['product_regular_price'];
productsalePrice = json['product_sale_price'];
thumbNail = json['thumbnail'];
qty = json['qty'];
lineSubTotal = double.parse(json['line_subtotal'].toString());
lineTotal = double.parse(json['line_total'].toString());
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['product_id'] = this.productId;
data['product_name'] = this.productName;
data['product_regular_price'] = this.productRegularPrice;
data['product_sale_price'] = this.productsalePrice;
data['thumbnail'] = this.thumbNail;
data['qty'] = this.qty;
data['line_subtotal'] = this.lineSubTotal;
data['line_total'] = this.lineTotal;
return data;
}
}
You need to login , then Testing this
I have an object that i want to send to an api through dio when i try this i get Unhandled Exception: DioError [DioErrorType.DEFAULT]: Converting object to an encodable object failed. I hav also tried converting the object to Json but i still get another error which i will mention down below.
static Future<DiagnosisModel> doDiagnosis(String url, String id,String choiceId, bool initial) async{
Dio dio = new Dio();
dio.options.headers['content-Type'] = 'application/json';
dio.options.headers['App-Id'] = ChatBotApi.applicationId;
dio.options.headers['App-Key'] = ChatBotApi.applicationKey;
Response response;
DiagnosisSendingModel diagnosisSendingModel;
Evidence evidence;
if(initial){
evidence = Evidence();
diagnosisSendingModel = DiagnosisSendingModel();
diagnosisSendingModel.evidence = List<Evidence>();
evidence.id = id;
evidence.initial = initial;
diagnosisSendingModel.sex = "male";
diagnosisSendingModel.age = 23;
diagnosisSendingModel.evidence.add(evidence);
response = await dio.post(
url,
data: diagnosisSendingModel
);
}else{
evidence = Evidence();
diagnosisSendingModel = DiagnosisSendingModel();
evidence.id = id;
if(choiceId == "present"){
evidence.choiceId = ChoiceId.PRESENT;
}else{
evidence.choiceId = ChoiceId.ABSENT;
}
diagnosisSendingModel.sex = "male";
diagnosisSendingModel.age = 23;
diagnosisSendingModel.evidence.add(evidence);
response = await dio.post(
url,
data: diagnosisSendingModel
);
}
DiagnosisModel diagnosisModel;
if(response.statusCode == 200){
diagnosisModel = DiagnosisModel.fromJson(response.data);
print(diagnosisModel);
}else{
throw("Error ${response.statusCode}");
}
return diagnosisModel;
}
I have also tried converting to json and i still get an error
Unhandled Exception: Converting object to an encodable object failed: Instance of 'DiagnosisSendingModel'
The code for that below
static Future<DiagnosisModel> doDiagnosis(String url, String id,String choiceId, bool initial) async{
Dio dio = new Dio();
dio.options.headers['content-Type'] = 'application/json';
dio.options.headers['App-Id'] = ChatBotApi.applicationId;
dio.options.headers['App-Key'] = ChatBotApi.applicationKey;
Response response;
DiagnosisSendingModel diagnosisSendingModel;
Evidence evidence;
if(initial){
evidence = Evidence();
diagnosisSendingModel = DiagnosisSendingModel();
diagnosisSendingModel.evidence = List<Evidence>();
evidence.id = id;
evidence.initial = initial;
diagnosisSendingModel.sex = "male";
diagnosisSendingModel.age = 23;
diagnosisSendingModel.evidence.add(evidence);
var jsonVar = json.encode(diagnosisSendingModel);
response = await dio.post(
url,
data: jsonVar
);
}else{
evidence = Evidence();
diagnosisSendingModel = DiagnosisSendingModel();
evidence.id = id;
if(choiceId == "present"){
evidence.choiceId = ChoiceId.PRESENT;
}else{
evidence.choiceId = ChoiceId.ABSENT;
}
diagnosisSendingModel.sex = "male";
diagnosisSendingModel.age = 23;
diagnosisSendingModel.evidence.add(evidence);
var jsonVar = json.encode(diagnosisSendingModel);
response = await dio.post(
url,
data: jsonVar
);
}
DiagnosisModel diagnosisModel;
if(response.statusCode == 200){
diagnosisModel = DiagnosisModel.fromJson(response.data);
print(diagnosisModel);
}else{
throw("Error ${response.statusCode}");
}
return diagnosisModel;
}
Below is my model
String sex;
int age;
List<Evidence> evidence;
ExtrasSending extras;
DiagnosisSendingModel({
this.sex,
this.age,
this.evidence,
this.extras,
});
factory DiagnosisSendingModel.fromJson(Map<String, dynamic> json) => DiagnosisSendingModel(
sex: json["sex"],
age: json["age"],
evidence: List<Evidence>.from(json["evidence"].map((x) => Evidence.fromJson(x))),
extras: ExtrasSending.fromJson(json["extras"]),
);
Map<String, dynamic> toJson() => {
"sex": sex,
"age": age,
"evidence": List<dynamic>.from(evidence.map((x) => x.toJson())),
"extras": extras.toJson(),
};
}
class Evidence {
String id;
ChoiceId choiceId;
bool initial;
Evidence({
this.id,
this.choiceId,
this.initial,
});
factory Evidence.fromJson(Map<String, dynamic> json) => Evidence(
id: json["id"],
choiceId: choiceIdValues.map[json["choice_id"]],
initial: json["initial"] == null ? null : json["initial"],
);
Map<String, dynamic> toJson() => {
"id": id,
"choice_id": choiceIdValues.reverse[choiceId],
"initial": initial == null ? null : initial,
};
}
enum ChoiceId { PRESENT, ABSENT }
final choiceIdValues = EnumValues({
"absent": ChoiceId.ABSENT,
"present": ChoiceId.PRESENT
});
class ExtrasSending {
bool enableTriage5;
ExtrasSending({
this.enableTriage5,
});
factory ExtrasSending.fromJson(Map<String, dynamic> json) => ExtrasSending(
enableTriage5: json["enable_triage_5"],
);
Map<String, dynamic> toJson() => {
"enable_triage_5": enableTriage5,
};
}
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;
}
} ```
replace :
var jsonVar = json.encode(diagnosisSendingModel);
with this:
var jsonVar = json.encode(diagnosisSendingModel.toJson());
try this
add in evironment variable C:\Users\<USER_NAME>\AppData\Local\Android\Sdk\platform-tools
open cmd write this adb reverse tcp:{portOfServer} tcp:{portOfServer}
exemple: adb reverse tcp:8081 tcp:8081
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
}