如何从Dart语言的Map结构中提取Country字段值?
如何从给定的Dart Map中提取Country字段的值
嘿,我来帮你搞定这个问题!你的Map里,"Countries"对应的是一个包含国家对象的数组,要提取其中的Country字段值,有几种实用的方式,我给你一一说明:
1. 提取单个国家的Country值(比如第一个)
如果只需要数组里某一个国家的名称,比如第一个,你可以这样写——记得加上空值判断,避免因为数据结构异常导致报错:
void main(){ var map = { "Countries":[ {"ID":"334d3cba-c305-4bd6-8da1-97bdc8273eec", "Country":"Afghanistan", "CountryCode":"AF", "Slug":"afghanistan", "NewConfirmed":0, "TotalConfirmed":161290, "NewDeaths":0, "TotalDeaths":7405, "NewRecovered":0, "TotalRecovered":0, "Date":"2022-01-30T07:14:34.603Z", "Premium":{} } ] }; // 安全提取第一个国家的名称 if (map["Countries"] != null && map["Countries"] is List && map["Countries"].isNotEmpty) { var firstCountryName = map["Countries"][0]["Country"]; print(firstCountryName); // 输出: Afghanistan } }
要是你能100%确定Countries数组一定存在且非空,也可以简化成map["Countries"][0]["Country"],但实际开发里还是建议保留判断,毕竟数据可能出现意外情况。
2. 提取所有国家的Country值到列表
如果以后Countries数组里有多个国家,想要把所有名称都提取出来,可以用Dart的Iterable.map方法:
void main(){ var map = { "Countries":[ {"ID":"334d3cba-c305-4bd6-8da1-97bdc8273eec", "Country":"Afghanistan", // 其他字段省略 }, {"ID":"222d3cba-xxxx-xxxx-xxxx-97bdc8273eee", "Country":"Albania", // 其他字段省略 } ] }; List<String> allCountryNames = []; if (map["Countries"] is List) { allCountryNames = (map["Countries"] as List) .map((countryObj) => countryObj["Country"] as String) .toList(); } print(allCountryNames); // 输出: [Afghanistan, Albania] }
这段代码会遍历Countries数组里的每一个对象,把每个对象的Country字段值提取出来,最后转成字符串列表。
3. 用自定义类让代码更清晰(进阶做法)
如果经常要处理这类国家数据,建议定义一个Country类,把Map转成实体对象——这样代码可读性更高,也不容易写错字段名:
class Country { final String id; final String name; final String code; // 你可以根据需要添加其他字段,比如TotalConfirmed、Date等 Country({required this.id, required this.name, required this.code}); // 从Map生成Country对象的工厂方法 factory Country.fromMap(Map<String, dynamic> map) { return Country( id: map["ID"] as String, name: map["Country"] as String, code: map["CountryCode"] as String, ); } } void main(){ var map = { "Countries":[ {"ID":"334d3cba-c305-4bd6-8da1-97bdc8273eec", "Country":"Afghanistan", "CountryCode":"AF", // 其他字段省略 } ] }; if (map["Countries"] is List) { List<Country> countries = (map["Countries"] as List) .map((e) => Country.fromMap(e as Map<String, dynamic>)) .toList(); String firstCountryName = countries.first.name; print(firstCountryName); // 输出: Afghanistan } }
用这种方式,你可以通过country.name来访问国家名称,IDE还会给你自动补全,开发起来更顺手。
内容的提问来源于stack exchange,提问作者jagnafukke
相关产品推荐
相关产品推荐

