[英]How to create a List<String> from a List<Map<String, String>> in Dart?
I have a Map
that looks like this 我有一张看起来像这样的Map
{
title: "Hello world",
images: [
{ url: "http://example.com/image1" },
{ url: "http://example.com/image2" },
{ url: "http://example.com/image3" }
]
}
and I need a List<String>
of the images that looks like this 我需要看起来像这样的图像的List<String>
[
"http://example.com/image1",
"http://example.com/image2",
"http://example.com/image3"
]
My current code looks like this 我当前的代码如下所示
List<String> images = [];
if( map['images'] is List<dynamic> ) {
map['images'].forEach((v) {
if (null != v['url'])
images.add(v['url']);
});
}
It works good, but I am curious if there is a one-liner that would accomplish the same thing in a neat (and error safe) way? 它的效果很好,但是我很好奇是否有一种单行代码能够以一种简洁(且安全无误)的方式完成同一件事?
var list = map['images'].map((innerMap) => innerMap['url']).toList()
I guess you are looking for something like this: 我想您正在寻找这样的东西:
var images = map['images'].where((m) => m['url'] != null).map((value) => value['url']).toList();
First we select all the items from map
that do not contain a null
field for url
. 首先,我们从map
中选择所有不包含url
null
字段的项目。 Then we map these url
values to a new List
. 然后,我们将这些url
值映射到新的List
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.