简体   繁体   中英

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]

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM