代码之家  ›  专栏  ›  技术社区  ›  Charles Jr

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

  •  0
  • Charles Jr  · 技术社区  · 7 年前

    我在这里创建了一个包含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”对类值进行排序。。。

    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]
    
    1 回复  |  直到 7 年前
        1
  •  7
  •   Hemanth Raj    7 年前

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

    如果你想要第三个 Top 在列表中 videos 你可以像这样访问它

    videos[3]
    

    如果你想重获财产 rank 第三个的 顶部 在列表中 视频 你可以像这样访问它

    videos[3].rank
    

    如果希望print语句显示列表中的项目,请将类更改为重写 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}";
     }
    }
    

    希望有帮助!