Home > OS >  How to find a value from List<Map<String, Object>> in dart(flutter)?
How to find a value from List<Map<String, Object>> in dart(flutter)?

Time:12-09

I have a list of all countries like this:

List<Map<String, Object>> allCountries = [
  {
    "name": "Afghanistan",
    "code": "AF",
    "capital": "Kabul",
    "region": "AS",
    "currency": {"code": "AFN", "name": "Afghan afghani", "symbol": "؋"},
    "language": {"code": "ps", "name": "Pashto"},
    "flag": "https://restcountries.eu/data/afg.svg",
    "dialling_code": " 93"
  },
   .................
  {
    "name": "Zimbabwe",
    "code": "ZW",
    "capital": "Harare",
    "region": "AF",
    "currency": {"code": "BWP", "name": "Botswana pula", "symbol": "P"},
    "language": {
      "code": "en",
      "iso639_2": "eng",
      "name": "English",
      "nativeName": "English"
    },
    "flag": "https://restcountries.eu/data/zwe.svg",
    "dialling_code": " 263"
  }

];

I want to create another List<Map<String, Object>> resultOfQuery from the original list but only when the query match or start with a name of country. How can this be done ?

CodePudding user response:

Use this method:

List<Map<String, Object>>filterByCountry(List<Map<String, Object>> list, String value){
   return list.where((mapObject) => (mapObject["name"] as String).startsWith(value)).toList(); 
  }

and you can use it like this:

print(filterByCountry(allCountries, "Afghan")); // will return List containing only the Map with the Afghanistan name
  • Related