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"
}
]
}
]
Related
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;
}
}
i'm new to learning darts and flutter i'm making code to display data with FutureBuilder, in console window i got the response i want, but the snapshot.hashData code always returns false
Myclass model
class ResponseDataBarang {
int? _kode;
String? _pesan;
List<Data>? _data;
ResponseDataBarang({int? kode, String? pesan, List<Data>? data}) {
if (kode != null) {
this._kode = kode;
}
if (pesan != null) {
this._pesan = pesan;
}
if (data != null) {
this._data = data;
}
}
int? get kode => _kode;
set kode(int? kode) => _kode = kode;
String? get pesan => _pesan;
set pesan(String? pesan) => _pesan = pesan;
List<Data>? get data => _data;
set data(List<Data>? data) => _data = data;
ResponseDataBarang.fromJson(Map<String, dynamic> json) {
_kode = json['kode'];
_pesan = json['pesan'];
if (json['data'] != null) {
_data = <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['kode'] = this._kode;
data['pesan'] = this._pesan;
if (this._data != null) {
data['data'] = this._data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String? _kdBrg;
String? _nmBrg;
Data(
{String? kdBrg,
String? nmBrg,
}) {
if (kdBrg != null) {
_kdBrg = kdBrg;
}
if (nmBrg != null) {
_nmBrg = nmBrg;
}
}
String? get kdBrg => _kdBrg;
set kdBrg(String? kdBrg) => _kdBrg = kdBrg;
String? get nmBrg => _nmBrg;
Data.fromJson(Map<String, dynamic> json) {
_kdBrg = json['KdBrg'];
_nmBrg = json['NmBrg'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['KdBrg'] = _kdBrg;
data['NmBrg'] = _nmBrg;
return data;
}
}
My request
i am confused for the json format as generated what return value is suitable for my method request
Future<ResponseDataBarang> ambilDataBarang() async {
Dio apiClient=ApiClient().init();
final response=await apiClient.post('http://192.168.1.8/aplikasikasir/data_barang.php', data: FormData.fromMap(({
"NmUser":"T",
})));
return ResponseDataBarang.fromJson(response.data);
}
}
Response i got
{"kode":1,"pesan":"Data Tersedia","data":[{"KdBrg":"170164017","NmBrg":"ST PP HONGNIE SANDAL","Harga":"38000","Stock_Akhir":"0","Sat_1":"PT","Sat_2":"","Sat_3":"","Sat_4":"","Isi_2":"0","Isi_3":"0","Isi_4":"0","KdSupl":"","NmSupl":"","Ket1":""}]}
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 this data format
message": [
{
"id": 15989,
"title": "xxx",
"body": "xxx",
"type": "abc",
"data_hash": "{\"id\":\"3098\",\"number\":1}",
}, .....]
If I write like this
print(message['data']['type']);
I can get abc, but if I write print(message['data']['data_hash']);, I get invalid arguments error. Why?
I want to get the number in data_hash.
This is the full code
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("===== onMessage ====");
try {
print(message['data']['data_hash']);
} catch (e) {
print(e.toString());
}
});
data_hash row is a json. So you need to decode that row for use.
final data_hash_map = jsonDecode(message['data']['data_hash']);
print(data_hash_map); // { "id": 3098, "number": 1 }
print(data_hash_map["number"]); // for number
Decode your json as below
Map<String, dynamic> jsonData = jsonDecode(message)
I recommend to create a class to predefine the object as followed:
class Message {
int id;
String title;
String body;
String type;
DataHash dataHash;
message({this.id, this.title, this.body, this.type, this.dataHash});
Message.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
body = json['body'];
type = json['type'];
dataHash = json['data_hash'] != null
? new DataHash.fromJson(json['data_hash'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['body'] = this.body;
data['type'] = this.type;
if (this.dataHash != null) {
data['data_hash'] = this.dataHash.toJson();
}
return data;
}
}
class DataHash {
String id;
String number;
DataHash({this.id, this.number});
DataHash.fromJson(Map<String, dynamic> json) {
id = json['id'];
number = json['number'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['number'] = this.number;
return data;
}
}
You can call Message.fromJson(data) to decode.
Messsage message = Message.fromJson(data);
print(message.dataHash.number);
I hope this will work correctly
class _HomeState extends State<Mytimeoff> {
List<Map> list = [];
Map leaveRoot ={};
void getList() async {
var data = await http
.get('https:your api link');
leaveRoot = Map.from(json.decode(data.body));
setState(() {
for (Map js in leaveRoot['leavetype']) {
list.add(js);
}
});
print(jsonData);
}
#override
void initState() {
super.initState();
getList();
}
#override
Widget build(BuildContext context) {
return Scaffold();
}
}