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}
Related
List<Cart> CARTLIST = [
Cart(productName: "productName", amount: 123, image: "image", quantity: 3, desc: "KG", prodId: 1),
Cart(productName: "productName", amount: 345, image: "image", quantity: 3, desc: "KG", prodId: 1),
];
How to get cart amount total?
I'd do:
var result = 0;
for (var cart in CARTLIST) {
result += cart.amount;
}
It's short, direct and readable.
If you insist on doing it in a single expression, you can do:
var result = CARTLIST.fold<int>(0, (acc, cart) => acc + cart.amount);
Or you can do it in more steps, first extract the amounts, then add them up:
var result = CARTLIST.map((cart) => cart.amount).reduce((v1, v2) => v1 + v2);
If the table has five columns i want to display only 2 columns for mobile view
https://ant.design/components/table
you can keep columns in component state and dynamically filter the columns on window resize. Something like this
useEffect(() => {
window.addEventListener("resize", <callback function to update columns>);
// cleanup
return() => window.removeEventListener("resize");
});
Inside render method you need to declare columns with let and change them if window.innerWidth < 480 (I made it less then 500 px to be safe). By changing, I mean filtering from an array of columns only those columns that you want. The best way to filter is by key, because it's unique. This is how the code looks in react:
import React, { PureComponent } from "react";
import { Table } from "antd";
export default class MainPage extends PureComponent {
renderMobileTable = columns => {
return columns.filter(
column => column.key === "name" || column.key === "city"
);
};
render() {
const dataSource = [
{
key: "1",
name: "Mike",
lastName: "Willins",
age: 32,
address: "10 Downing Street",
city: "Chicago"
},
{
key: "2",
name: "John",
lastName: "Billards",
age: 42,
address: "5th Blvd",
city: "New York"
}
];
let columns = [
{
title: "Name",
dataIndex: "name",
key: "name"
},
{
title: "Last Name",
dataIndex: "lastName",
key: "lastName"
},
{
title: "Age",
dataIndex: "age",
key: "age"
},
{
title: "Address",
dataIndex: "address",
key: "address"
},
{
title: "City",
dataIndex: "city",
key: "city"
}
];
const isMobile = window.innerWidth < 500;
if (isMobile) {
columns = this.renderMobileTable(columns);
}
return <Table dataSource={dataSource} columns={columns} />;
}
}
For the source code you may refer to my repository on GitHub.
NOTE: if you are testing mobile view in Chrome Dev Tools, make sure you reload the page after resizing, as we put the logic into render method and the application has to be re-rendered or reloaded.
In antd v4 you can use column prop 'responsive'
const columns = [{
title: 'identification number',
dataIndex: 'ID',
responsive: ['sm'],
}]
https://ant.design/components/table/#Column
I want to create a nested hash using four values type, name, year, value. ie, key of the first hash will be type, value will be another hash with key name, then value of that one will be another hash with key year and value as value.
The array of objects I'm iterating looks like this:
elements = [
{
year: '2018',
items: [
{
name: 'name1',
value: 'value1',
type: 'type1',
},
{
name: 'name2',
value: 'value2',
type: 'type2',
},
]
},
{
year: '2019',
items: [
{
name: 'name3',
value: 'value3',
type: 'type2',
},
{
name: 'name4',
value: 'value4',
type: 'type1',
},
]
}
]
And I'm getting all values together using two loops like this:
elements.each do |element|
year = element.year
element.items.each |item|
name = item.name
value = item.value
type = item.type
# TODO: create nested hash
end
end
Expected output is like this:
{
"type1" => {
"name1" => {
"2018" => "value1"
},
"name4" => {
"2019" => "value4"
}
},
"type2" => {
"name2" => {
"2018" => "value2"
},
"name3" => {
"2019" => "value3"
}
}
}
I tried out some methods but it doesn't seems to work out as expected. How can I do this?
elements.each_with_object({}) { |g,h| g[:items].each { |f|
h.update(f[:type]=>{ f[:name]=>{ g[:year]=>f[:value] } }) { |_,o,n| o.merge(n) } } }
#=> {"type1"=>{"name1"=>{"2018"=>"value1"}, "name4"=>{"2019"=>"value4"}},
# "type2"=>{"name2"=>{"2018"=>"value2"}, "name3"=>{"2019"=>"value3"}}}
This uses the form of Hash#update (aka merge!) that employs a block (here { |_,o,n| o.merge(n) } to determine the values of keys that are present in both hashes being merged. See the doc for definitions of the three block variables (here _, o and n). Note that in performing o.merge(n) o and n will have no common keys, so a block is not needed for that operation.
Assuming you want to preserve the references (unlike in your desired output,) here you go:
elements = [
{
year: '2018',
items: [
{name: 'name1', value: 'value1', type: 'type1'},
{name: 'name2', value: 'value2', type: 'type2'}
]
},
{
year: '2019',
items: [
{name: 'name3', value: 'value3', type: 'type2'},
{name: 'name4', value: 'value4', type: 'type1'}
]
}
]
Just iterate over everything and reduce into the hash. On the structures of known shape is’s a trivial task:
elements.each_with_object(
Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) } # for deep bury
) do |h, acc|
h[:items].each do |item|
acc[item[:type]][item[:name]][h[:year]] = item[:value]
end
end
#⇒ {"type1"=>{"name1"=>{"2018"=>"value1"},
# "name4"=>{"2019"=>"value4"}},
# "type2"=>{"name2"=>{"2018"=>"value2"},
# "name3"=>{"2019"=>"value3"}}}
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
I have following data contract available in constant variable data
[
{
id: 1,
name: "class1",
start_at: "2017-08-15T10:00:00.000Z",
end_at: "2017-08-15T10:30:00.000Z",
},
{
id: 2,
name: "class2",
start_at: "2017-08-15T10:00:00.000Z",
end_at: "2017-08-15T10:30:00.000Z",
},
......more data here.....
]
I want to return the specific set of data.
e.g data.select {|e| e[:id] = 1} should return following but instead it returns all data.
[
{
id: 1,
name: "class1",
start_at: "2017-08-15T10:00:00.000Z",
end_at: "2017-08-15T10:30:00.000Z",
}
]
Any idea what is wrong?
extracted_data = data.select {|e| e[:id] == 1}
== for comparison