Charles Jr Charles Jr - 6 months ago 83
Dart Question

How to retrieve properties from a List of Class in Dart?

I created a custom Class with 4 elements here...

class Top {
String videoId;
int rank;
String title;
String imageString;

Top({this.videoId, this.rank, this.title, this.imageString});
}


I'm retrieving some Firebase items to populate these elements..

var top = new Top(videoId: items['vidId'], rank: items['Value'],
title: items['vidTitle'], imageString: items['vidImage']);


Then I'm adding them to a List of Type "Top" in order to sort the Class values based on "rank"...

List<Top> videos = new List();
videos..sort((a, b) => a.rank.compareTo(b.rank));
videos.add(top);


But, printing
videos
logs this...

[Instance of 'Top', Instance of 'Top', Instance of 'Top', Instance of 'Top', Instance of 'Top', Instance of 'Top', Instance of 'Top', Instance of 'Top']


I'm not sure if its because its in a List. How can I get usable "Top" property values from videos? For instance when I query
top.rank
I get this...

[14, 12, 11, 10, 10, 6, 5, 1]

Answer Source

The properties of a list is obtained with [] operator passing the index of the element.

If you wanted retrive third Top in the list videos you can just access it like

videos[3]

If you wanted retrive a property rank of third Top in the list videos you can just access it like

videos[3].rank

If you want the print statement tho show items of list, then change your class to override toString method, like

class Top {
  String videoId;
  int rank;
  String title;
  String imageString;

 Top({this.videoId, this.rank, this.title, this.imageString});

 @override
 String toString(){
     return "{videoId: $videoId, rank: $rank, title: $title, imageString: $imageString}";
 }
}

Hope that helped!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download