如何从 Dart 中的 Class 列表中检索属性?
How to retrieve properties from a List of Class in Dart?
我在这里创建了一个包含 4 个元素的自定义 Class...
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" 属性 值?例如,当我查询 top.rank
我得到这个...
[14, 12, 11, 10, 10, 6, 5, 1]
列表的属性是通过 []
运算符传递元素索引获得的。
如果您想检索列表中的第三个 Top
videos
,您可以像
一样访问它
videos[3]
如果你想检索列表中第三个 Top
的 属性 rank
videos
你可以像
一样访问它
videos[3].rank
如果您希望打印语句显示列表项,请更改您的 class 以覆盖 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}";
}
}
希望对您有所帮助!
我在这里创建了一个包含 4 个元素的自定义 Class...
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" 属性 值?例如,当我查询 top.rank
我得到这个...
[14, 12, 11, 10, 10, 6, 5, 1]
列表的属性是通过 []
运算符传递元素索引获得的。
如果您想检索列表中的第三个 Top
videos
,您可以像
videos[3]
如果你想检索列表中第三个 Top
的 属性 rank
videos
你可以像
videos[3].rank
如果您希望打印语句显示列表项,请更改您的 class 以覆盖 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}";
}
}
希望对您有所帮助!