A Map related error in flutter which happens everytime I try to parse it - flutter

I have a map which contains two standard key and value pairs like
_body = {
"expected_time": "$Time",
"payment": "$payment",
"receiver" : {},
};
And another map named receiver inside it as you can see. Values are being passed to the receiver later using a for loop and the information is being added just fine.
for(int i=0; i<=n; i++)
{
_body['receiver'][i] = {
"receiver_name" : "abc",
};
}
The issue I'm facing is when trying to send this map to an api call via http.post
there jsonEncode(body) has been used to encode the map to send it. When sending those simple key value pairs I'm getting no error but when I'm trying to include the receiver field as well I'm getting the error.
Can anyone please tell me what I need to here? Thanks!

you are not making it in the right way, try this
var _body = {
"expected_time": "time",
"payment": "payment",
"receiver" : {},
};
for(int i=0; i<=3; i++) {
_body.addAll({
'receiver[$i]': {
"receiver_name": "abc",
}
});
}
print(_body);
and the output is like this
{expected_time: time, payment: payment, receiver: {}, receiver[0]: {receiver_name: abc}, receiver[1]: {receiver_name: abc}, receiver[2]: {receiver_name: abc}, receiver[3]: {receiver_name: abc}}
you can now encode it

Related

Flutter : can't get all response body from get request

I have get request in Flutter app, when I test the request in postman I get all data, something like this :
{
"result":{
"name" : "somename",
"images":[
"test.jpg",
"test2.jpg"
],
"sizes":[
{
"id": 1,
"value" : 5
},
{
"id": 2,
"value" : 15
}
]
}
}
I call data and print them like this without using models:
var data = json.decode(response.body);
print(data['result']['name']);
print(data['result']['images']);
print(data['result']['sizes']);
it is print all things expect last one.
where must be the mistake?
Solved, by adding "?sizesView = true" to the link
final response = await http.get(path +'?sizesView = true'):
you should get the index of the last one because it is in a dictionary not a list do this:
print(data['result']['sizes'][0]['id']) // it will get the first index of the sizes list and then get the id key
or you can creat a model of list to get the indexes of your list

Storing List into Firestore In Multiple Map

Hi I wanted to store a List into Firestore.
I am working on a project and in this page I will need to select some selection (selection is the DocumentID) and store it in a List, After that I need to retrieve from the List and call Firestore again to get the GeoPoint of the item based on the List (the List contains the DocumentID). Then I am able to retrieve that as well thanks to the help of the community. But now I can only store one of the Item of the List and not all of them.
This is my code:
void initRoute(data, dataInt) async{
Firestore.instance.collection('routes').document(inputName).setData({
dataInt:{
"Lat" : data['location'].latitude,
"Lng" : data['location'].longitude
}
});
}
I am able to store but it only store the first Item in the List into the Firestore. How can i store all of them into just 1 Document with few Map something similar to the picture below.
And also the name of the Map can I generate it based on how many items I have in the list (1st item get 0, 2nd item get 1 and so on...)and add it in when storing? Thank you so much in advance.
Edit:
The dataInt is meant to do the numbering but I failed miserably but still do not know how to get it work.
Update:
I am getting all the List from Firestore.
Firstly the we select some from here:
Then the after selecting it will store the Name into the List
Code of using the List:
List<String> _selectedBusStop = List<String>();
Code of adding to List when onTap and onLongPress
onTap: (){
if(_selectedBusStop.contains(user.data['BusstopName'])){
setState(() {
_selectedBusStop.removeWhere((val) => val == user.data['BusstopName']);
});
}
},
onLongPress: (){
setState(() {
_selectedBusStop.add(user.data['BusstopName']);
});
}
Because the List only have the BusstopName saved in it so I will need to read again from Firestore and get the GeoPoint that I needed. Saved it in a Map and use it as a Polyline. Now I am currently stuck at where I am unable to save all of the Item in the List into the Firestore when I am calling the setData as it only save 1 of the item in the List and I want to store all of it.
Sorry for causing misunderstanding again. Really sorry for that.
Update I am able to store all of the Item in my List into Firestore
void initRoute(data, dataInt) async{
Firestore.instance.collection('routes').document(inputName).setData({
data['BusstopName']:{
"Lat" : data['location'].latitude,
"Lng" : data['location'].longitude
}
}, merge: true);
}
with this code.
First create a Map locally, give it the int you want:
Map<String,dynamic> dataToBeSent ={
'0': {
"Lat" : data['location'].latitude,
"Lng" : data['location'].longitude}
}
Now, before sending to firebase, you know if this is the first LatLng or not, if it's the first, you use .set, like this:
Firestore.instance.collection('routes').document(inputName).setData(dataToBeSent);
This will create a new document, with the coordinates inside a Map and it has the index you want. Later on, you want to add another LatLng to this document, you use .update, and send the new Map.
Map<String,dynamic> dataToBeSent2 ={
'2': {
"Lat" : data['location'].latitude,
"Lng" : data['location'].longitude}
}
Firestore.instance.collection('routes').document(inputName).updateData(dataToBeSent2);
This will keep updating the keys you are sending, but be careful to not store a new map using the same id, for example 0, it will over write what is currently at key 0 in firebase.
Based on your edits and comment replies, first start with this:
void initRoute(data, dataInt) async{
if(data.isNotEmpty){
for(int a = 0; a < data; a++){
Map<String,dynamic> dataToBeSent={
$a:{
"Lat" : data['location'].latitude,
"Lng" : data['location'].longitude
}
};
Firestore.instance.collection('routes').document(inputName).setData(dataToBeSent);
}
}
}

Passing values from an API through another API discord.js

So what trying to do is get some values I get from an API, pass onto an array to THEN pass it through another API and then add up the data it gets.
I already made this fetching it from 1 api, but I don't know how to fetch all the values from one api, pass it into an array, and fetch each value for each item.
let req1 = `https://inventory.roblox.com/v1/users/${imageURL}/assets/collectibles?sortOrder=Asc&limit=100`
let req2 = `https://users.roblox.com/v1/users/${imageURL}`
function getItems() {
return axios.get(req1)
}
function getUser() {
return axios.get(req2)
}
await Promise.all([getItems(), getUser(),getValue()])
.then(function(response){
let rap = response[0].data.data
let items = response[0].data.data.assetId
let itemarray = 0
let value = response[2].data.items[items array goes here][4]
let sum = 0
for(let i = 0; i < rap.length; i++) {sum += response[0].data.data[i].recentAveragePrice}
this is what I have so far. Any help will be appreciated. Thanks.
Edit:
Heres what req1 spits out:
{
"previousPageCursor": null,
"nextPageCursor": "49034821991_1_a887f8ff3a6b076aafd71c91a5a4a4fb",
"data": [
{
"userAssetId": 23726188,
"serialNumber": null,
"assetId": 7636350,
"name": "Supa Fly Cap",
"recentAveragePrice": 23535,
"originalPrice": null,
"assetStock": null,
"buildersClubMembershipType": 0
},
{
"userAssetId": 1329942875,
"serialNumber": 13717,
"assetId": 113325603,
"name": "Recycled Cardboard Shades",
"recentAveragePrice": 5703,
"originalPrice": 25,
"assetStock": 15000,
"buildersClubMembershipType": 0
},
```
req2 doesnt apply for this part of the code :p

Getting Cannot read property in postman scripts when null found

I am getting an Error when running a script in the Postman Tests tab, When trying to check that a property is not null.
My JSON response:
{
"statusMessage": "Success",
"timeStamp": "2018-01-23 05:13:16.7",
"numberOfRecords": 7,
"parties": [
{
"shippingAddress": null,
"shippingDetails": null,
"paExpirationDate": "",
"historyDate": "01/22/2018",
"renewal": {
"renewalRx": "N",
"priorRxNumber": "",
"priorSB": "",
"priorFillNumber": ""
},
"noOfRefillingRemaining": "1",
"ndc": "00074-3799-06",
"rxId": "7004942",
"fillingNumber": "0"
},
{
"shippingAddress": {
"addressLine1": "2150 St",
"addressLine2": "Home Line 2",
"city": "Bronx",
"state": "NY",
"zipCode": "10453",
"addressSeqNumber": "1",
"medFacilityIndicator": "N"
}
}
]
}
My postman script is:
var jsonData = JSON.parse(responseBody);
var parties = jsonData.parties;
parties.forEach(function(data){
if(data.shippingAddress!==null && data.shippingAddress.addressLine1 !== null ){
postman.setEnvironmentVariable("addressLine1",data.shippingAddress.addressLine1);
}
I am getting the following error:
"Error running tests for results: TypeError: Cannot read property 'addressLine1' of null"
You could try this, I changed your code slightly but this would work:
var parties = pm.response.json().parties
for(i = 0; i < parties.length; i++) {
if(parties[i].shippingAddress !== null) {
pm.environment.set("addressLine1", parties[i].shippingAddress.addressLine1)
}
}
I tested this locally with the Schema that you provided and that it wrote 2150 St to my environment file.
The schema you posted doesn't seem to be a complete one, I think that the parties array has a shippingAddress property which is either null or it is an object containing the shippingAddress details - I might be wrong but I can't get my head around the data that you posted.
I don't think what you're searching on the in the if statement is correct and it wouldn't work the way you have it because if the first condition is null (like in your response data) it wouldn't ever meet the second condition because the object wouldn't be there and that shippingAddress.addressLine1 reference would always show that error.
Or you could use your code like this:
var jsonData = JSON.parse(responseBody)
var parties = jsonData.parties
parties.forEach(function(data) {
if(data.shippingAddress !== null) {
postman.setEnvironmentVariable("addressLine1",data.shippingAddress.addressLine1)
}
})

Handling nested callbacks/promises with Mongoose

I am a beginner with Node.js and Mongoose. I spent an entire day trying to resolve an issue by scouring through SO, but I just could not find the right solution. Basically, I am using the retrieved values from one collection to query another. In order to do this, I am iterating through a loop of the previously retrieved results.
With the iteration, I am able to populate the results that I need. Unfortunately, the area where I am having an issue is that the response is being sent back before the required information is gathered in the array. I understand that this can be handled by callbacks/promises. I tried numerous ways, but I just haven't been successful with my attempts. I am now trying to make use of the Q library to facilitate the callbacks. I'd really appreciate some insight. Here's a snippet of the portion where I'm currently stuck:
var length = Object.keys(purchasesArray).length;
var jsonArray = [];
var getProductDetails = function () {
var deferred = Q.defer();
for (var i = 0; i < length; i++) {
var property = Object.keys(purchasesArray)[i];
if (purchasesArray.hasOwnProperty(property)) {
var productID = property;
var productQuery = Product.find({asin:
productQuery.exec(function (err, productList) {
jsonArray.push({"productName": productList[0].productName,
"quantity": purchasesArray[productID]});
});
}
}
return deferred.promise;
};
getProductDetails().then(function sendResponse() {
console.log(jsonArray);
response = {
"message": "The action was successful",
"products": jsonArray
};
res.send(response);
return;
}).fail(function (err) {
console.log(err);
})
});
I am particularly able to send one of the two objects in the jsonArray array as the response is being sent after the first element.
Update
Thanks to Roamer-1888 's answer, I have been able to construct a valid JSON response without having to worry about the error of setting headers after sending a response.
Basically, in the getProductDetails() function, I am trying to retrieve product names from the Mongoose query while mapping the quantity for each of the items in purchasesArray. From the function, eventually, I would like to form the following response:
response = {
"message": "The action was successful",
"products": jsonArray
};
where, jsonArray would be in the following form from getProductDetails :
jsonArray.push({
"productName": products[index].productName,
"quantity": purchasesArray[productID]
});
On the assumption that purchasesArray is the result of an earlier query, it would appear that you are trying to :
query your database once per purchasesArray item,
form an array of objects, each containing data derived from the query AND the original purchasesArray item.
If so, and with few other guesses, then the following pattern should do the job :
var getProductDetails = function() {
// map purchasesArray to an array of promises
var promises = purchasesArray.map(function(item) {
return Product.findOne({
asin: item.productID // some property of the desired item
}).exec()
.then(function product {
// Here you can freely compose an object comprising data from :
// * the synchronously derived `item` (an element of 'purchasesArray`)
// * the asynchronously derived `product` (from database).
// `item` is still available thanks to "closure".
// For example :
return {
'productName': product.name,
'quantity': item.quantity,
'unitPrice': product.unitPrice
};
})
// Here, by catching, no individual error will cause the whole response to fail.
.then(null, (err) => null);
});
return Promise.all(promises); // return a promise that settles when all `promises` are fulfilled or any one of them fails.
};
getProductDetails().then(results => {
console.log(results); // `results` is an array of the objects composed in getProductDetails(), with properties 'productName', 'quantity' etc.
res.json({
'message': "The action was successful",
'products': results
});
}).catch(err => {
console.log(err);
res.sendStatus(500); // or similar
});
Your final code will differ in detail, particularly in the composition of the composed object. Don't rely on my guesses.