skip to Main Content

I have a map as below in Flutter/Dart.

Map currencyMap = {status: Success, currency: [{id: 1, code: AFN, currency: Afghan afghani, rate: 0.25}, {id: 2, code: EUR, currency: European euro, rate: 0.25}, {id: 3, code: CFA, currency: Franc CFA, rate: 0.25}]}

How do i extract just the codes to a list like below.

currencyList = [AFN, EUR, CFA]

2

Answers


  1. UPDATE

    Here is a more better version (using a map) in just one line.

    List<dynamic> currencyList = currencyMap["currency"].map((entry) => entry["code"]).toList();
    print(currencyList);
    

    Try this – old version using a loop

    void main() {
    
      List currencyList = [];
      Map currencyMap = {
        "status": "Success",
        "currency": [{
            "id": "1",
            "code": "AFN",
            "currency": "Afghan afghani",
            "rate": "0.25"
        }, {
            "id ": "2",
            "code": "EUR",
            "currency": "European euro",
            "rate ": "0.25"
        }]
      };
      
      for(var currency in currencyMap["currency"]) {
         currencyList.add(currency["code"]);
      }
       
      print(currencyList);
    
    }
    
    Login or Signup to reply.
  2. You can try this:

    List currency = currencyMap["currency"] as List
    
    List currencyList = currency?.map((value)=> {
      return value["code"]
    }).toList();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search