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.
CodePudding user response:
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]);
CodePudding user response:
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}