如何从列表内的地图获取地图值列表?

时间:2020-01-05 20:30:21

标签: dart

假设我有一个这样的列表!

List<Map<String, String>> names = [
  {'name': 'John'},
  {'name': 'Adam'},
  {'name': 'Sean'},
  {'name': 'Shirley'},
  {'name': 'Samantha'},
];

我如何只能检索地图中的值列表?

我希望输出为:

List<String> names = [
  'John',
  'Adam',
  'Sean',
  'Shirley',
  'Samantha',
];

1 个答案:

答案 0 :(得分:2)

类似这样的东西:

void main() {
  List<Map<String, String>> names = [
    {'name': 'John'},
    {'name': 'Adam'},
    {'name': 'Sean'},
    {'name': 'Shirley'},
    {'name': 'Samantha'},
  ];

  final onlyNames1 = names.map((map) => map.values.first).toList();
  final onlyNames2 = names.expand((map) => map.values).toList();
  print(onlyNames1); // [John, Adam, Sean, Shirley, Samantha]
  print(onlyNames2); // [John, Adam, Sean, Shirley, Samantha]
}