颤振如何显示列表中的单个值? [英] Flutter how to show single value from List?

查看:39
本文介绍了颤振如何显示列表中的单个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数组中筛选数据,然后只需要从数据中获取一个值即可.其显示的是过滤后的数据,但需要知道如何从该数据中显示一个值?

I am trying to filter data from array and then need to just a single value from data. Its showing filtered data but need to know how can i show a single value from that data ?

class _ViewPostScreenState extends State<ViewPostScreen> {
List showPost;
String data;


  @override
  void initState(){
    super.initState();
    print(widget.id);
    showPost = posts.where((i) => i.id == widget.id).toList();
    data = showPost.toString();
    print(data);

  }

数据的响应或打印输出是此 I/flutter(7374):[{id:0,authorName:Umaiz Khan,authorImageUrl:assets/images/user0.png,timeAgo:5分钟,imageUrl:资产/图片/post0.jpg}]

The response or print output of data is this I/flutter ( 7374): [{id: 0, authorName: Umaiz Khan, authorImageUrl: assets/images/user0.png, timeAgo: 5 min, imageUrl: assets/images/post0.jpg}]

我需要知道如何仅显示此数据中的authorName?

I need to know how can I just show the authorName from this data?

类似这样的打印内容(data.authorName);尝试这样做但不起作用.

something like this print(data.authorName); try to do like this but not working.

这里的数据看起来像其他文件中的

Here my data look like in other file

class Post {
  String authorName;
  String authorImageUrl;
  String timeAgo;
  String imageUrl;
  int id;

  Post({
    this.authorName,
    this.authorImageUrl,
    this.timeAgo,
    this.imageUrl,
    this.id,
  });

  @override
  String toString() {
    return '{id: $id, authorName: $authorName, authorImageUrl: $authorImageUrl, timeAgo: $timeAgo, imageUrl: $imageUrl}';
  }
}

final List<Post> posts = [
  Post(
    id: 0,
    authorName: 'Umaiz Khan',
    authorImageUrl: 'assets/images/user0.png',
    timeAgo: '5 min',
    imageUrl: 'assets/images/post0.jpg',
  ),
  Post(
    id: 1,
    authorName: 'Saad ahmed',
    authorImageUrl: 'assets/images/user1.png',
    timeAgo: '10 min',
    imageUrl: 'assets/images/post1.jpg',
  ),
  Post(
    id: 2,
    authorName: 'Hiba',
    authorImageUrl: 'assets/images/user4.png',
    timeAgo: '10 min',
    imageUrl: 'assets/images/post2.jpg',
  ),
];

推荐答案

当您要基于其中对象的值来获取任何列表时,可以始终使用此for循环,在这种情况下,widget.id应该是等同于帖子的ID

You can always use this for loop when you want to fetch any list base on value of an object inside it, where in your case the widget.id should be equivalent to an id of a post

@override
  void initState() {
    super.initState();
    print(widget.id);

    Post getPost(int postID) {
      for (int i = 0; i < posts.length; i++) {
        if (posts.elementAt(i).id == postID) {
          return posts.elementAt(i);
        }
      }
      return null;
    }

    print(getPost(widget.id).authorName);
  }

我希望有帮助

这篇关于颤振如何显示列表中的单个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆