How to calculate the tatal using .reduce on dart map - dart

I have a map like this:
{id2: {quantity: 6, name: NEW NAME}, 1484: {quantity: 1, name: NEW NAME 404}, id: {quantity: 34, name: NEW NAME}}
here I have a key called "quantity" what i need to do is calculate the total quantity , for this example 6+1+34 = 41 , maybe using .reduce method but can't find how to implement it on a map.

I think it make more sense to use fold which you can read about here: https://api.dart.dev/stable/2.10.5/dart-core/Iterable/fold.html
void main() {
final map = {
'id2': {'quantity': 6, 'name': 'NEW NAME'},
1484: {'quantity': 1, 'name': 'NEW NAME 404'},
'id': {'quantity': 34, 'name': 'NEW NAME'}
};
final sum = map.values
.fold(0, (int sum, element) => sum + (element['quantity'] as int));
print(sum); // 41
}
But if you really want to use reduce you can do it like this:
void main() {
final map = {
'id2': {'quantity': 6, 'name': 'NEW NAME'},
1484: {'quantity': 1, 'name': 'NEW NAME 404'},
'id': {'quantity': 34, 'name': 'NEW NAME'}
};
final sum =
map.values.map((e) => e['quantity'] as int).reduce((a, b) => a + b);
print(sum); // 41
}

Related

Finding the index of an object containing a matching element

I have a List of Objects in the file list.dart:
final itemList = [
ItemData(uuid: 'one', score: '30', title: 'Title One', description: 'mock description'),
ItemData(uuid: 'two', score: '10', title: 'Title Two', description: 'mock description'),
ItemData(uuid: 'three', score: '20', title: 'Title Three', description: 'mock description'),
];
I am calling back UUID: 'one' to another widget in the file edit.dart
return GestureDetector(
onTap: (){
currentItem = item.uuid; //currentItem declared in file edit.dart
DisplayItem(); //callback function to edit.dart
},
child: Card(
My plan is to use the callback function to get the elements with the corresponding uuid. My problem is I can't figure out how to find the index of the object with the element equal to a given uuid. I've tried nesting indexOf() but get exponentially confused.
So if I understand correctly, you have a list of items and you want to find the index of the first item that fulfils a condition (in this case the condition is that the items UUID value is equal to some value)
In order to do something like that, you can use the indexWhere method:
var targetUuid = 'one';
int itemIndex = itemList.indexWhere((item) => item.uuid == targetUuid);
print(itemList[itemIndex]);
you can find the index of object as:
void main() {
final List<Map<String, dynamic>> _people = [
{"id": "c1", "name": "John Doe", "age": 40},
{"id": "c2", "name": "Kindacode.com", "age": 3},
{"id": "c3", "name": "Pipi", "age": 1},
{"id": "c4", "name": "Jane Doe", "age": 99},
];
// Find index of the person whose id = c3
final index1 = _people.indexWhere((element) => element["id"] == "c3");
if (index1 != -1) {
print("Index $index1: ${_people[index1]}");
}
// Find the last index where age > 80
final index2 = _people.lastIndexWhere((element) => element["age"] > 80);
if (index2 != -1) {
print("Index $index2: ${_people[index2]}");
}
}
Output:
Index 2: {id: c3, name: Pipi, age: 1}
Index 3: {id: c4, name: Jane Doe, age: 99}

How to make each parameter appear in a table row?

I have a device that get some telemetry data via REST API. Some of the data that it received is in the following format:
{
...
parameters: [
{
'name': 'parameter1',
'grade': '2',
'info': 'some informtion'
},
{
'name': 'parameter2',
'grade': '1',
'info': 'some informtion'
},
...
]
}
what I want to do is to visualize the data in the following way:
name | grade | info
---------------------------------------
parameter1 | 2 | some information
parameter2 | 1 | some information
... | ... | ...
now if I break down each parameter and send it to the device separately it will override the previous one.
How can I make that?
Figured out a way to do this:
Go to 'Widget Bundle' and create a new widget bundle.
Create a new widget of type 'Latest values'.
Here we have CSS/HTML section and a Javascript section.
HTML section:
<div class="my-data-table">
</div>
Javascript section:
self.defaultList = [
{
'id': 1,
'name': 'name 1',
'grade': 123,
'description': 'This is a description'
},
{
'id': 2,
'name': 'name 2',
'grade': 456,
'description': 'More description'
},
{
'id': 3,
'name': 'name 3',
'grade': 789,
'description': 'Even more description'
}
];
self.createTable = function(data) {
const columnNames = Object.keys(data[0]);
let tableHeadContent = $('<tr></tr>');
columnNames.forEach((columName) => {
tableHeadContent.append('<td>' + columName + '</td>');
});
let tableHead = $('<thead></thead>').append(tableHeadContent);
let tableBody = $('<tbody></tbody>');
data.forEach((currentElement, index) => {
const vals = Object.values(currentElement);
let currentRow = $('<tr></tr>');
vals.forEach((val) => {
currentRow.append('<td>' + val + '</td>');
});
tableBody.append(currentRow);
});
return $('<table></table>').append(tableHead).append(tableBody);
}
self.onInit = function() {
let currentList = [...self.defaultList];
if(self.ctx.defaultSubscription.data[0].data.length !== 0) {
currentList = JSON.parse(self.ctx.defaultSubscription.data[0].data[0][1]);
}
let currentTable = self.createTable(currentList);
$('.my-data-table', self.ctx.$container).append(currentTable);
}
self.onDataUpdated = function() {
self.ctx.detectChanges();
}
What you need to pay attention to and understand is self.ctx.defaultSubscription.data, when you visualize your data with a certain widget you subscribe the data to the widget. self.ctx.defaultSubscription.data give you access to the data, you can console.log() it to see how it is structured.
The self.defaultList is for the preview and when you set this widget to a specific data it will use that data.
There may be other way to do this but this is how I did it.

Different row data in Nested Table Row

I am using Ant Design for my project. I have a scene where i should use Ant Design Nested Table where in every row opens new nested Table to show data. I am not able to show different data for each row. It is showing same data in all Nested rows
This is what i am using
https://ant.design/components/table/#components-table-demo-nested-table
Code is as such from Official Doc
Expecting to show different data in different nested row items
Inside expandedrow function you can pass a row parameter. Based on the row you can render your own table.
https://codesandbox.io/s/34w7km6o11
In the above sample, you can check how i rendered different data based on that particular row.
I used ternary operator, You can write your own condition
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Table } from "antd";
const columns = [
{ title: "Name", dataIndex: "name", key: "name" },
{ title: "Age", dataIndex: "age", key: "age" },
{ title: "Address", dataIndex: "address", key: "address" },
{
title: "Action",
dataIndex: "",
key: "x",
render: () => Delete
}
];
const data = [
{
key: 1,
name: "John Brown",
age: 32,
address: "New York No. 1 Lake Park",
description:
"My name is John Brown, I am 32 years old, living in New York No. 1 Lake Park."
},
{
key: 2,
name: "Jim Green",
age: 42,
address: "London No. 1 Lake Park",
description:
"My name is Jim Green, I am 42 years old, living in London No. 1 Lake Park."
},
{
key: 3,
name: "Joe Black",
age: 32,
address: "Sidney No. 1 Lake Park",
description:
"My name is Joe Black, I am 32 years old, living in Sidney No. 1 Lake Park."
}
];
const data1 = [
{
key: 1,
name: "I am diff",
age: 32,
address: "New York No. 1 Lake Park",
description:
"My name is John Brown, I am 32 years old, living in New York No. 1 Lake Park."
},
{
key: 2,
name: "yes",
age: 42,
address: "London No. 1 Lake Park",
description:
"My name is Jim Green, I am 42 years old, living in London No. 1 Lake Park."
},
{
key: 3,
name: "no",
age: 32,
address: "Sidney No. 1 Lake Park",
description:
"My name is Joe Black, I am 32 years old, living in Sidney No. 1 Lake Park."
}
];
const data2 = [
{
key: 1,
name: "hello",
age: 32,
address: "New York No. 1 Lake Park",
description:
"My name is John Brown, I am 32 years old, living in New York No. 1 Lake Park."
},
{
key: 2,
name: "hi",
age: 42,
address: "London No. 1 Lake Park",
description:
"My name is Jim Green, I am 42 years old, living in London No. 1 Lake Park."
},
{
key: 3,
name: "test",
age: 32,
address: "Sidney No. 1 Lake Park",
description:
"My name is Joe Black, I am 32 years old, living in Sidney No. 1 Lake Park."
}
];
const expandedRow = row => {
console.log(row);
let inTable = row.key == 1 ? data1 : row.key == 2 ? data2 : data;
return <Table columns={columns} dataSource={inTable} pagination={false} />;
};
ReactDOM.render(
<Table columns={columns} expandedRowRender={expandedRow} dataSource={data} />,
document.getElementById("container")
);
I have a different approach to this problem, I have been looking around in other posts and have not found this solution, I hope it helps:
import React from "react";
import "antd/dist/antd.css";
import { Table } from "antd";
import { fakeFirstLevelData } from
'../fakeDataBase/fakeFirstLevelData'
const firstLevelColumns = [
{
title: 'ID',
dataIndex: 'id_tx',
key: 'ID_TX'
},
{
title: 'Amount',
dataIndex: 'amount',
key: 'amount'
},
{
title: 'Currency',
dataIndex: 'currency',
key: 'currency'
},
]
const secondLevelColumns = [
{
title: 'First name from',
dataIndex: 'firstname_from',
key: ''
},
{
title: 'first name to',
dataIndex: 'firstname_to',
key: ''
},
{
title: 'Date ',
dataIndex: 'date',
key: ''
},
]
const firstExpandedRow = (record, index, indent, expanded) => {
let data = []
data.push(record.secondLevel)
return (
<Table
rowKey={record => record.cardholderid}
columns={secondLevelColumns}
dataSource={data}
// expandable={{ expandedRowRender: secondExpandedRow }}
pagination={false}
/>
)
}
return (
<div className='container mt-40 mb-40 overflow-x-auto
tableContainer'>
<Table
dataSource={fakeFirstLevelData}
columns={firstLevelColumns}
rowKey={record => record.id_tx}
loading={fakeFirstLevelData ? false : true}
pagination={false}
expandable={{
expandedRowRender: firstExpandedRow,
defaultExpandAllRows: false
}}
/>
</div>
)
This is my fake data , its similar to call a API:
export const fakeFirstLevelData = [
{
id: '1199343457',
amount: '127,45',
currency: 'EUR',
secondLevel: {
firstnameFrom: 'Antonio',
firstnameTo: 'Juan',
date: '2024/12/12'
}
},
{
id: '11993453458',
amount: '1',
currency: 'EUR',
secondLevel: {
firstnameFrom: 'Carlos',
firstnameTo: 'Estefanía',
date: '2024/12/12'
}
}
]
This way I have a json with different levels of information and in each row I can show N fields and by expanding the rows I can show more information of the same row.
make children data with state
then pass it to the expan function
write the parameter with free text
then inside nested table write data[expan.key].children2 inside datasource of nested table.
data[expan.key].children2 is just free text you can change with other. thank you

Dependent lists no ajax

I'm using select2 v4 and trying to make dependent lists with local (already loaded) choices.
var list1 = [
{id: 42, name: 'xxx'},
{id: 43, name: 'yyy'}
];
var list2 = [
{id: 1, name: 'aaa', list1: 42},
{id: 2, name: 'bbb', list1: 42},
{id: 3, name: 'ccc', list1: 43},
{id: 4, name: 'ddd', list1: 43}
]
I'd like list2 to depend on list1
I tried to use a callback on data:
$('#list1').select2({
data: list1
});
$('#list2').select2({
data: function () {
var list2_filtered = $.grep(list2, function (choice) {
return choice.list1 == $('#list1').val();
});
return list2_filtered;
}
});
but it does not seem to be called.
Why is my callback function never called ?
How can I make these local lists dependent ?
Refreshing a select2 data is a quite known issue.
So I implemented my own "data updater":
function refreshSelect($input, data) {
$input.html($('<option />')); // if a default blank is needed
for (var key in data) {
var $option = $('<option />')
.prop('value', data[key]['id'])
.text(data[key]['text'])
;
$input.append($option)
}
$input.trigger('change');
}
Here is how to use it:
<select id="my_select_input"></select>
var $input = $('#my_select_input');
var data = [
{
id: 42,
text: 'XX'
},
{
id: 43,
text: 'YY'
}
];
refreshSelect($input, data);
It works with and without select2

Generate tds outside each input field in dart

This is my first question on stackoverflow and i'm totally newbie to dartlang.
I have 8 input fields which i created using this:
InputElement in1 = new InputElement();
in1.placeholder = "№";
InputElement in2 = new InputElement();
in2.placeholder = "Name";
...
InputElement in8 = new InputElement();
in8.placeholder = "Date";
And i couldn't figure out how to automatically generate row with tds containing those input fields. If i create it manually my code would look like this:
InputElement in1 = new InputElement();
in1.placeholder = "№";
TableCellElement cell1 = new Element.td();
cell1.nodes.add(in1);
InputElement in2 = new InputElement();
in2.placeholder = "Name";
TableCellElement cell2 = new Element.td();
cell2.nodes.add(in2);
InputElement in3 = new InputElement();
in3.placeholder = "LastName";
TableCellElement cell3 = new Element.td();
cell3.nodes.add(in3);
InputElement in4 = new InputElement();
in4.placeholder = "Register No";
TableCellElement cell4 = new Element.td();
cell4.nodes.add(in4);
InputElement in5 = new InputElement();
in5.placeholder = "University";
TableCellElement cell5 = new Element.td();
cell5.nodes.add(in5);
InputElement in6 = new InputElement();
in6.placeholder = "Occupation";
TableCellElement cell6 = new Element.td();
cell6.nodes.add(in6);
InputElement in7 = new InputElement();
in7.placeholder = "Grade";
TableCellElement cell7 = new Element.td();
cell7.nodes.add(in7);
InputElement in8 = new InputElement();
in8.placeholder = "Date";
TableCellElement cell8 = new Element.td();
cell8.nodes.add(in8);
TableRowElement tr1 = new Element.tr();
tr1.classes.add("table-header-student");
tr1.nodes.add(cell1);
tr1.nodes.add(cell2);
tr1.nodes.add(cell3);
tr1.nodes.add(cell4);
tr1.nodes.add(cell5);
tr1.nodes.add(cell6);
tr1.nodes.add(cell7);
tr1.nodes.add(cell8);
I don't wanna create it manually cuz i need to do it on other tables with different columns. And the reason i'm creating these input field is to create filtering.
Pls don't suggest innerHtml, appendHtml cuz i have to create it with purely dart code.
I think it's possible to do by making list and using loop but i don't know how. Pls help me!
I'm not sure if I understand your question correctly but I assume this is what you want.
List<String> placeholders = ['№', 'Name', 'LastName', 'Register No', 'University', 'Occupation', 'Grade', 'Date'];
TableRowElement tr = new Element.tr()
..classes.add("table-header-student");
placeholders.forEach((ph) {
tr.append(new TableCellElement()..append(new InputElement()..placeholder = ph));
});
querySelector('table').append(tr);
example with more attributes (not tested)
List<String> fields = [
{'placeholder': '№', 'id': 'id1', 'name': 'name1'},
{'placeholder': 'Name', 'id': 'id2', 'name': 'name2'},
{'placeholder': 'LastName', 'id': 'id3', 'name': 'name3'},
{'placeholder': 'Register No', 'id': 'id4', 'name': 'name4'},
{'placeholder': 'University', 'id': 'id5', 'name': 'name5'},
{'placeholder': 'Occupation', 'id': 'id6', 'name': 'name6'},
{'placeholder': 'Grade', 'id': 'id7', 'name': 'name7'},
{'placeholder': 'Date', 'id': 'id8', 'name': 'name8'}];
TableRowElement tr = new Element.tr()
..classes.add("table-header-student");
fields.forEach((f) {
tr.append(new TableCellElement()..append(
new InputElement()
..placeholder = f['placeholder']
..id = f['id']
..name = f['name']
));
});
querySelector('table').append(tr);
If your element creation logic becomes more complicated I would create a function/method for this
main() {
List<String> fields = [
{'placeholder': '№', 'id': 'id1', 'name': 'name1'},
{'placeholder': 'Name', 'id': 'id2', 'name': 'name2'},
{'placeholder': 'LastName', 'id': 'id3', 'name': 'name3'},
{'placeholder': 'Register No', 'id': 'id4', 'name': 'name4'},
{'placeholder': 'University', 'id': 'id5', 'name': 'name5'},
{'placeholder': 'Occupation', 'id': 'id6', 'name': 'name6'},
{'placeholder': 'Grade', 'id': 'id7', 'name': 'name7'},
{'placeholder': 'Date', 'id': 'id8', 'name': 'name8'}];
TableRowElement tr = new Element.tr()
..classes.add("table-header-student");
fields.forEach((f) {
tr.append(new TableCellElement()..append(createInputElement(f));
});
querySelector('table').append(tr);
}
InputElement createInputElement(Map metadata) {
var ie = new InputElement();
if(metadata['placeholder'] != null) ie.placeholder = metadata['placeholder'];
if(metadata['id'] != null) ie.id = metadata['id'];
if(metadata['name'] != null) ie.name = metadata['name'];
// ... more element customization
return ie;
}

Resources