繁体   English   中英

如何从Dart中的类列表检索属性?

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

我在这里创建了一个包含4个元素的自定义类...

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

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

我正在检索一些Firebase项来填充这些元素。

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

然后我将它们添加到“ Top”类型的列表中,以便基于“ rank”对Class值进行排序...

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

但是,打印videos记录此信息...

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

我不确定是否是因为它在列表中。 如何从视频中获得可用的“热门”属性值? 例如,当我查询top.rank我得到了...

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

列表的属性是通过[]运算符传递元素的索引来获得的。

如果你想retrive第三Top列表中的videos你可以访问它像

videos[3]

如果您想在列表videos rank在第三Top ,请按以下方式访问它:

videos[3].rank

如果要使打印语句显示列表项,请更改类以覆盖toString方法,例如

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}";
 }
}

希望能有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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