skip to Main Content

I have a list of Map that contains bank data and now for creating chart it requires key and value..

void main() {
  List<Map<String, dynamic>> maplist = [
    {
      'Bank': 'HDFC',
      'Balance': 10900.00,
      'Transactions': []
    },

    {
      'Bank': 'AXIS',
      'Balance': 5900.00,
      'Transactions': []
    },


    {
      'Bank': 'UCO',
      'Balance': 4200.00,
      'Transactions': []
    },
    {
      'Bank': 'ICICI',
      'Balance': 2300.00,
      'Transactions': []
    },

    {
      'Bank': 'KOTAK',
      'Balance': 1200.00,
      'Transactions': []
    },
  ];
  Map<String, double> chartData = {};
 
  // i want following result in chartData
      {
    'HDFC':10900, 'AXIS':5900,'UCO':4200,'OTHERS':3500}
  }

}

it should take first 3 banks and fourth key ‘OTHERS’ should be present sum of all other bank’s balance

2

Answers


  1. just use this function for that:

    Map<String, double> mapTpChartData(List<Map<String, dynamic>> maplist) {
      Map<String, double> chartData = {};
      for (var map in maplist) {
        chartData[map['Bank']] = map['Balance'];
      }
      return chartData;
    }
    

    Full example is:

    void main() {
      List<Map<String, dynamic>> maplist = [
        {'Bank': 'HDFC', 'Balance': 10900.00, 'Transactions': []},
        {'Bank': 'AXIS', 'Balance': 5900.00, 'Transactions': []},
        {'Bank': 'UCO', 'Balance': 4200.00, 'Transactions': []},
        {'Bank': 'ICICI', 'Balance': 2300.00, 'Transactions': []},
        {'Bank': 'KOTAK', 'Balance': 1200.00, 'Transactions': []},
      ];
    
      Map<String, double> chartData = mapTpChartData(maplist);
    
    
      print(chartData);
      // {HDFC: 10900, AXIS: 5900, UCO: 4200, ICICI: 2300, KOTAK: 1200}
    
    }
    
    Map<String, double> mapTpChartData(List<Map<String, dynamic>> maplist) {
      Map<String, double> chartData = {};
      for (var map in maplist) {
        chartData[map['Bank']] = map['Balance'];
      }
      return chartData;
    }
    
    Login or Signup to reply.
  2. This should work for you required case.

    Map<String, double> chartData = {
      maplist[0]["Bank"]: maplist[0]["Balance"],
      maplist[1]["Bank"]: maplist[1]["Balance"],
      maplist[2]["Bank"]: maplist[2]["Balance"],
      "OTHERS": maplist
          .sublist(3)
          .fold(0, (previousValue, element) => previousValue + element["Balance"]),
    };
    

    We are getting first 3 elements and for others we are doing summation of all balances.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search