Dart/Flutter How to access element of Map inside a list - flutter

How to access a Map element value by key, when a Map is inside a list?
'rooms': [
{
'roomNumber': 1,
'roomBeds': 1,
'roomColor': 1,
'roomNumOfDwellers': 0,
'roomDwellers': [
]
},
{
'roomNumber': 2,
'roomBeds': 3,
'roomColor': 2,
'roomNumOfDwellers': 0,
'roomDwellers': [
]
},
]
Tried this, doesn't work:
myPODO.rooms[1].['roomBeds']
The error message is:
Class '_InternalLinkedHashMap' has no instance getter 'roomBeds'.
Receiver: _LinkedHashMap len:5
Tried calling: roomBeds

Store the items in a list of Map and you can then print the values by key names.
void main() {
List<Map<String, dynamic>> rooms = [
{
'roomNumber': 1,
'roomBeds': 1,
'roomColor': 1,
'roomNumOfDwellers': 0,
'roomDwellers': [
]
},
{
'roomNumber': 2,
'roomBeds': 3,
'roomColor': 2,
'roomNumOfDwellers': 0,
'roomDwellers': [
]
},
];
print(rooms[1]['roomBeds']);
}

try to replace
myPODO.rooms[1].['roomBeds']
with
myPODO.rooms[1]['roomBeds']

Related

Flutter : How change modify unmodifiable map

I have list like this in provider:
List orders=[]:
void getOrders(){
orders = [
{"id":1,
"order":[
{"id":1,"name":"mike"},
{"id":2,"name":"john"},
{"id":3,"name":"smith"}
]
},
{"id":1,
"order":[
{"id":1,"name":"roz"},
{"id":2,"name":"sam"},
{"id":3,"name":"ruby"}
]
},
];
notifyListeners();
}
in provider when I use this methos to chane indexed order with another:
void changeOrder(orderIndex,item){
orders[orderIndex].update("order",(val)=>item);
notifyListeners();
}
I get this error type '(dynamic) => dynamic' is not a subtype of type '(Object) => Object' of 'update'
and when I use this :
void changeOrder(orderIndex,item){
orders[orderIndex]["order"]=item;
notifyListeners();
}
I get this error Unsupported operation: Cannot modify unmodifiable map
Add More Details
the item in changeOrder method comes from screen contain orders :
var item = List.from(orders[index]);
orders type is List<Map<String, dynamic>>. While reading the item, it will be a map instead of list.
Map item = Map.from(orders[index]);
And you can use both way you;ve tried.
List<Map<String, dynamic>> orders = [];
void getOrders() {
orders = [
{
"id": 1,
"order": [
{"id": 1, "name": "mike"},
{"id": 2, "name": "john"},
{"id": 3, "name": "smith"}
]
},
{
"id": 1,
"order": [
{"id": 1, "name": "roz"},
{"id": 2, "name": "sam"},
{"id": 3, "name": "ruby"}
]
},
];
}
void changeOrder(orderIndex, item) {
orders[orderIndex]["order"] = item;
// orders[orderIndex].update("order", (val) => item);
}
void main(List<String> args) {
getOrders();
print(orders);
Map item = Map.from(orders[1]);
changeOrder(1, item);
print(orders);
}

how to store every element of api response list to a List<String> in flutter?

I have to Store Every Element of List to List so how i can do this?
Json Response as below.
{
"responseCode": 200,
"responseMessage": "OK",
"data": null,
"dataList": [
"Technical",
"Field"
],
"excelDataList": null,
"totalRecords": 2,
"pageRecords": 0,
"currentPageNumber": 1,
"totalPages": 0
}
Here i have to store dataList values in list.
You first have to call jsonDecode to convert your String into deserialized data, then you can use the [] operator to access individual keys.
Read more at
import "dart:convert";
const String apiResult = """{
"responseCode": 200,
"responseMessage": "OK",
"data": null,
"dataList": [
"Technical",
"Field"
],
"excelDataList": null,
"totalRecords": 2,
"pageRecords": 0,
"currentPageNumber": 1,
"totalPages": 0
}
""";
void main() {
Map<String, dynamic> des = jsonDecode(apiResult);
List<dynamic> data = des["dataList"];
print(data);
}
which would print
> [Technical, Field]

What is the cleanest way to get the average of each item list in Dart?

I have a List<Expenses> in dart. It looks like this:
[
{itemId: 1,
quantity: 10.0
},
{itemId: 2,
quantity: 14.0
},
{itemId: 2,
quantity: 25.0
},
{itemId: 3,
quantity: 3.0
}
...
];
I would like to get the average of each itemId to obtain a List like this:
[
{itemId: 1,
quantity: 10.0
},
{itemId: 2,
quantity: 19.5
},
{itemId: 3,
quantity: 3.0
}
...
];
What is the simplest way to do that?
I wouldn't say it is the simplest but it works:
void main() {
List data = [
{"itemId": 1, "quantity": 10.0},
{"itemId": 2, "quantity": 14.0},
{"itemId": 2, "quantity": 25.0},
{"itemId": 3, "quantity": 3.0}
];
List formattedList(List list) {
var obj = {};
for (var i = 0; i < list.length; i++) {
if (obj[list[i]["itemId"]] == null) {
obj[list[i]["itemId"]] = {"count": 1, "quantity": list[i]["quantity"]};
} else {
obj[list[i]["itemId"]]["count"] += 1;
obj[list[i]["itemId"]]["quantity"] += list[i]["quantity"];
}
}
List sol = [];
for (var key in obj.keys) {
sol.add({"itemId": key, "quantity": obj[key]["quantity"] / obj[key]["count"]});
}
return sol;
}
print(formattedList(data));
}

MongoDB , add and format fields on array result

I have this document:
[{
_id: "5a9eff23b9eea111a00016c8",
participants: [
2,
3
]
}]
I would like to know if it's possible to add and format fields on array result, something like this.
{
_id: "5a9eff23b9eea111a00016c8",
participants: [
{
_id: 2,
order: 22,
},
{
_id: 3,
order: 22,
}
]
}
This should not be saved in the database, it should be only attached on response.
If it's possible, I would like an advice.
#rollstuhlfahrer
Well , i don't think so , these fields ( order , _id) , doesn't exists in other table , they are custom
I've figured it out. Works well. Done in PHP.
I've used $map , see the documentation below.
https://docs.mongodb.com/manual/reference/operator/aggregation/map/
[
'$project' => [
'_id' => 0,
'title' => '$title',
'participants' => [
'$map' => [
'input' => '$participants',
'as' => 'part',
'in' => [
'recipient' => '$$part',
'status' => false,
]
]
]
]]
Here is the result:
{
title: "Channel#O4ScAPkYLz",
participants: [
{
recipient: 2,
status: false
},
{
recipient: 1,
status: false
}
]
}

TreeModel.parse pass array?

I'm using the TreeModel js library. It looks like the library supports passing a object that has a structure like...
{
id: 1,
children: [{
id: 2,
childre: []
}]
}
However, what if I have a tree structure that is an array like...
[
{
id: 1,
children: [],
},
{
id: 2,
children: [
id: 5,
children []
]
}
]
Does the library not support passing an array? Thoughts on how best to deal with this?
You can create a fake root (id=0) whose children are your array:
{
id: 0,
children: [
{
id: 1,
children: [],
},
{
id: 2,
children: [
id: 5,
children []
]
}
]
}