Flutter how to show single value from List?

守給你的承諾、 提交于 2021-01-29 05:43:17

问题


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);

  }

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}]

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

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',
  ),
];

回答1:


Change String data to Post data

data = showPost[0];




回答2:


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

I hope this help



来源:https://stackoverflow.com/questions/61129266/flutter-how-to-show-single-value-from-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!