[英]List<Map<String,dynamic>> to List<String> Dart
I am new to programming.我是编程新手。 I have a List<Map<String,dynamic>> of data and I want to create a List of Strings from map values.我有一个 List<Map<String,dynamic>> 数据,我想从 map 值创建一个字符串列表。 Here is my sample data.这是我的示例数据。 Let's say I need a list of product names in Dart.假设我需要 Dart 中的产品名称列表。 Appreciate your help.Thanks.感谢您的帮助。谢谢。
final products = [
{'productimage': 'image1.jpg', 'productprice': '800', 'productid': '1234', 'productname': 'rabbittoy'},
{'productimage': 'image2.jpg', 'productprice': '400', 'productid': 'p10001', 'productname': 'mousetoy'},
{'productid': '4533', 'productprice': '1800', 'productimage': 'image3.jpg', 'productname': 'cat'},
{'productname': 'dog', 'productid': 'p10002', 'productimage': 'image4.jpg', 'productprice': '3000'}
];
If your list was assigned to a variable called products
I would use .map()
to do the following:如果您的列表被分配给名为products
的变量,我将使用.map()
执行以下操作:
final productNames = products.map((Map<String, dynamic> product) {
return product["productname"];
}).toList();
I'm using .toList()
at the end because .map()
returns an Iterable
object rather than a List
object.我最后使用.toList()
因为.map()
返回一个Iterable
object 而不是List
object。 I couldn't give you a 100% answer on why but you can read about it here .我不能给你一个 100% 的答案,但你可以在这里阅读。
You could use the fold
method:您可以使用fold
方法:
List<String> productNames = data.fold<List<String>>(
[], (prev, element) => List.from(prev)..add(element['productname']));
Full snippet example:完整片段示例:
void main() {
List<Map<String, dynamic>> data = [
{
'productimage': 'image1.jpg',
'productprice': '800',
'productid': '1234',
'productname': 'rabbittoy'
},
{
'productimage': 'image2.jpg',
'productprice': '400',
'productid': 'p10001',
'productname': 'mousetoy'
},
{
'productid': '4533',
'productprice': '1800',
'productimage': 'image3.jpg',
'productname': 'cat'
},
{
'productname': 'dog',
'productid': 'p10002',
'productimage': 'image4.jpg',
'productprice': '3000'
}
];
List<String> productNames = data.fold<List<String>>(
[], (prev, element) => List.from(prev)..add(element['productname']));
print(productNames); // [rabbittoy, mousetoy, cat, dog]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.