How can I get the index of a custom-object-element in a List<customClass> using an object property?

1,577

You can use indexWhere
the following code has tested in Dardpad
full code

import 'dart:async';
import 'dart:io';
import 'dart:core';
import 'dart:convert';
import 'dart:html';

class Student{
  String name;
  int age;  
  Student(this.name, this.age);
} 

main()  {  

  List<Student> studentsList = [];

  studentsList.add(Student('Jack', 16));
  studentsList.add(Student('Tamer', 17));
  studentsList.add(Student('Dido', 18));
  studentsList.add(Student('Lili', 15));

  int index = studentsList.indexWhere((st) => st.name=='Dido' && st.age==18); 
  print(index);

}
Share:
1,577
Mimina
Author by

Mimina

Updated on December 14, 2022

Comments

  • Mimina
    Mimina over 1 year

    I have a custom Class 'Student' that has two properties 'name' & 'age'. In my main method, I've created a List of this custom class, List, and added 4 Student objects to the List. My question is, how can I get the index of one of the objects using any of the object's propertied?

    For example how can I get the index of Student('Dido', 18)?

    void main() {
      List<Student> studentsList = [];
      studentsList.add(Student('Jack', 16));
      studentsList.add(Student('Tamer', 17));
      studentsList.add(Student('Dido', 18));
      studentsList.add(Student('Lili', 15));    
    }
    
    class Student{
      String name;
      int age;  
      Student(this.name, this.age);
    }