class product {
String name;
String price;
String quantity;
product({this.name, this.price, this.quantity});
}
void main() {
List<product> listofProducts = [
product(name: "A", price: "10"),
product(name: "B", price: "10"),
product(name: "C", price: "10"),
product(name: "D", price: "10"),
product(name: "E", price: "10"),
product(name: "F", price: "10")
];
print(listofProducts.indexOf(product(name: "B", price: "10")));
}
How do I find the index of the product(name: "B", price: "10") in listofProducts list.
since the items of your list are not primitve, they are reference types , you need to use the indexWhere method on the list
final index = listofProducts.indexWhere((product) => product.name == "B" && product.price == "10");
print(index)
this way you iterate over each element of the array of products and find the index of that item. becuase you are having reference types as items.
Alternative you can override == and hashCode so you change what Dart understands as equal of Product objects (default behavior is that objects are only equal if they are the same instance in memory).
By doing the following we change it so two Product objects are equal if they have the same name, price and quantity values.
import 'package:quiver/core.dart';
class Product {
String name;
String price;
String quantity;
Product({this.name, this.price, this.quantity});
#override
bool operator ==(dynamic other) {
if (other is Product) {
return other.name == name &&
other.price == price &&
other.quantity == quantity;
}
return false;
}
#override
int get hashCode => hash3(name, price, quantity);
}
void main() {
List<Product> listofProducts = [
Product(name: "A", price: "10"),
Product(name: "B", price: "10"),
Product(name: "C", price: "10"),
Product(name: "D", price: "10"),
Product(name: "E", price: "10"),
Product(name: "F", price: "10")
];
print(listofProducts.indexOf(Product(name: "B", price: "10"))); // 1
}
To implement the hashCode I can recommend use the quiver package which has the hash3 method to make it more convenient to combine the hash of 3 values.
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);
I have the following list in Dart, which is a List of Map which maps a key to a list of MyClass objects:
class MyClass {
final String name;
final int age;
MyClass({
required this.name,
required this.age,
});
}
void main() {
MyClass obj1 = MyClass(name: "aa", age: 10);
MyClass obj2 = MyClass(name: "bb", age: 20);
MyClass obj3 = MyClass(name: "cc", age: 30);
MyClass obj4 = MyClass(name: "dd", age: 40);
MyClass obj5 = MyClass(name: "ee", age: 50);
MyClass obj6 = MyClass(name: "ff", age: 60);
List<Map<String, List<Object>>> myList = [
{ '3' : [obj1, obj2]},
{ '1' : [obj3, obj4]},
{ '2' : [obj5, obj6]},
];
print(myList);
}
I need to sort this list based on keys in descending order so that keys need to be in the order '3', '2', '1' in the main list.
How can I do this?
You can give sort() on List a compare method which define how elements should be sorted. So in your case, we can do something like this:
void main() {
List<Map<String, List<MyClass>>> myList = [
{ '3' : [MyClass(name: 'ifredom',age:23), MyClass(name: 'aaa',age:13)]},
{ '1' : [MyClass(name: 'JackMa',age:61), MyClass(name: 'bbb',age:33)]},
{ '2' : [MyClass(name: 'zhazhahui',age:48), MyClass(name: 'ccc',age:29)]}
];
myList.forEach(print);
// {3: [MyClass(name: ifredom, age: 23), MyClass(name: aaa, age: 13)]}
// {1: [MyClass(name: JackMa, age: 61), MyClass(name: bbb, age: 33)]}
// {2: [MyClass(name: zhazhahui, age: 48), MyClass(name: ccc, age: 29)]}
myList.sort((a, b) => b.keys.first.compareTo(a.keys.first));
myList.forEach(print);
// {3: [MyClass(name: ifredom, age: 23), MyClass(name: aaa, age: 13)]}
// {2: [MyClass(name: zhazhahui, age: 48), MyClass(name: ccc, age: 29)]}
// {1: [MyClass(name: JackMa, age: 61), MyClass(name: bbb, age: 33)]}
}
class MyClass {
final String name;
final int age;
MyClass({required this.name, required this.age,});
#override
String toString() => 'MyClass(name: $name, age: $age)';
}
Notice that we do assume here that each Map in your first List only contains one key and then sort based on this.
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}
I have two different arrays which am trying to map them to one object, using the information in the first array ModelOne id. I use two for loops to check if the id in model one appears in the second array if true create an object with model one id, name and array of all names in model two. From my implementation am not able to get the correct results.
// Model One
struct ModelOne: Codable {
let id: Int
let name: String
}
// Model two
struct ModelTwo: Codable {
let id: Int
let modelOneId: Int
let name: String
}
var arrayOne = [ModelOne]()
arrayOne.append(ModelOne(id: 1, name: "One"))
arrayOne.append(ModelOne(id: 2, name: "Two"))
var arrayTwo = [ModelTwo]()
arrayTwo.append(ModelTwo(id: 1, modelOneId: 1, name: "Some name"))
arrayTwo.append(ModelTwo(id: 2, modelOneId: 1, name: "Other name"))
arrayTwo.append(ModelTwo(id: 1, modelOneId: 2, name: "Name one"))
arrayTwo.append(ModelTwo(id: 2, modelOneId: 2, name: "Name two"))
struct MappedModel {
let id: Int
let name: String
let items: [String]
}
var arrayThree = [MappedModel]()
for i in arrayOne {
for x in arrayTwo {
if i.id == x.id {
arrayThree.append(MappedModel(id: i.id, name: i.name, items: [x.name]))
}
}
}
If I'm interpreting the issue correctly, you want the MappedModel to have the id and name from ModelOne, with items containing all of the names from the ModelTwo where modelOneId matches the ModelOne id.
If so, this would do the trick:
var combined = arrayOne.map { item1 in
MappedModel(id: item1.id, name: item1.name, items: arrayTwo.compactMap { $0.id == item1.id ? $0.name : nil})
}
Which yields:
[
MappedModel(id: 1, name: "One", items: ["Some name", "Other name"]),
MappedModel(id: 2, name: "Two", items: ["Name one", "Name two"])
]
please help me!
List<String> Id= ["MES9-7t73JhFzAEoL6J","MES91YJevIAthak253M"];
List<Product> products =
[
Product(
id: 'MES9-2',
categories: 'AC1, AC2, AC3, N1, Pn1, P',
title: 'Red Shirt',
description: 'A red shirt - it is pretty red!',
price: 29.99,
imageUrl:
'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-tshirt-1710578_1280.jpg',
),
Product(
categories:' pn2, N2, N3, Pn2, Pn3',
id: 'MES91YJevIAthak253M',
title: 'Trousers',
description: 'A nice pair of trousers.',
price: 59.99,
imageUrl:
'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Trousers%2C_dress_%28AM_1960.022-8%29.jpg/512px-Trousers%2C_dress_%28AM_1960.022-8%29.jpg',
),
];
=> How to extract product from list of _items where product id is same as String in Id List.
Try this:
final product = products.firstWhere((p) => Id.contains(p.id));
You need to run two for loops to extract list of products corresponding to list of products ids you have. First loop will run according to the length of ids you have got and second according to the length of products. It will match both ids in the if condition and add the matching products to foundProducts list.
findProducts(){
List<Product> foundProducts = [];
for(int i=0; i<listOfIds.length;++i){
for(int j=0; j<productList.length; ++j){
if(listOfIds[i] == productList[j].id){
foundProducts.add(productList[j]);
}
}
}
}
You just have to iterate over your list, and find the match and return it. You can do via firsWhere().
So, you will have to iterate over your Id using list iterate dart
//you have the List<Product> we are taking the variable as products
List<Product> products = ....
// this will store the item which matches the id
var item;
Id.forEach((id){
//now using first where
products.firstWhere((item) => item.id == id, orElse: () => null);
});
// now printing the item and check for the nullability
print(item ?? 'No products found'); // You will get the matching the Product matching the item id
Please note: firstWhere(), gives out the first item found in the list matching the any of the ids. So you will single product only. I am assuming for the single requirement only.
I have a demo for you. Here you can make out how this works
DEMO
class Product {
double price;
String id, categories, title, description, imageUrl;
Product({
this.id,
this.categories,
this.title,
this.description,
this.price,
this.imageUrl
});
}
void main() {
var result;
List<String> id = ["MES9-7t73JhFzAEoL6J","MES91YJevIAthak253M"];
List<Product> products = [
Product(
id: 'MES9-2',
categories: 'AC1, AC2, AC3, N1, Pn1, P',
title: 'Red Shirt',
description: 'A red shirt - it is pretty red!',
price: 29.99,
imageUrl:
'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
),
Product(
categories:' pn2, N2, N3, Pn2, Pn3',
id: 'MES91YJevIAthak253M',
title: 'Trousers',
description: 'A nice pair of trousers.',
price: 59.99,
imageUrl:
'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Trousers%2C_dress_%28AM_1960.022-8%29.jpg/512px-Trousers%2C_dress_%28AM_1960.022-8%29.jpg',
)
];
// Here is what we're doing the main operation
id.forEach((id){
result = products.firstWhere((item) => item.id == id, orElse: () => null);
});
//printing the result
print(result ?? "No items found");
// similary you can get the result item via result.id
print("RESULT: ${result.id}, ${result.categories}, ${result.title}");
}
Output
Instance of 'Product' // so this is the instance of the product
RESULT: MES91YJevIAthak253M, pn2, N2, N3, Pn2, Pn3, Trousers