How to create a List<String> from a List<Map<String, String>> in Dart?
Solution 1
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
. Then we map these url
values to a new List
.
Solution 2
var list = map['images'].map((innerMap) => innerMap['url']).toList()
Magnus
I have delivered value. But at what cost? Bachelor of Science degree in Computer Engineering. ✪ Started out on ATARI ST BASIC in the 1980's, writing mostly "Look door, take key" type games. ✪ Spent a few years in high school writing various small programs for personal use in Delphi. ✪ Learned PHP/SQL/HTML/JS/CSS and played around with that for a few years. ✪ Did mostly Android and Java for a few years. ✪ Graduated from Sweden Mid University with a BSc in Computer Engineering. At this point, I had learned all there was to know about software development, except where to find that darn "any" key... ✪ Currently working with Flutter/Dart and Delphi (again).
Updated on December 09, 2022Comments
-
Magnus over 1 year
I have a
Map
that looks like this{ 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[ "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?
-
J. Almandos over 5 yearsSmooth solution.
-
Magnus over 5 yearsI prefer this solution, as it checks that the
url
key actually exists and the value is non-null!