Richard Kyle
Richard Kyle

Reputation: 51

Flutter Dart : How to convert List to Map with 2 key

I have a problem converting a list to a Map, I'm using map.fromiterable to convert my list, but it only can show 1 data and 1 key. This is what it output:

[{id_apd: 4}]

here is my class Model for the list,

class APDPengajuanModel {
  final int id_apd;
  final int jumlah;

  APDPengajuanModel({this.id_apd, this.jumlah});

}

and here is my function to convert the list to a map.

void toMap() {
Map<String, dynamic> id_apd = Map.fromIterable(
        Provider.of<myProvider>(context, listen: false).listAPD,
        key: (v) => "id_apd",
        value: (v) => v.id_apd.toString());
print(id_apd);
}

from my code above, it only can show id_apd and can't show jumlah variables from the list.

please help how to show id_apd and jumlah together :)

this is how the output that i hope, but not shows like this.

[
  {
    "id_apd": 1,
    "jumlah" : 15
  }
]

Upvotes: 1

Views: 5994

Answers (3)

malik kurosaki
malik kurosaki

Reputation: 2042

I assume you have 2 lists that you want to combine into a list map

final listPengajuan = ["id_apd","jumlah"];
final nilai = [1,5];

final paket = {};
final hasil = [];

 for(var i = 0; i < listPengajuan.length; i++){
  paket.addAll({listPengajuan[i]:nilai[i]});
 }
 
 hasil.add(paket);

 print(JsonEncoder.withIndent(" ").convert(hasil));

result :

[
 {
  "id_apd": 1,
  "jumlah": 5
 }
]

Upvotes: 2

KuKu
KuKu

Reputation: 7492

I think that there is difference between what title means and output you hope. This is code for result you hope.

var result = listAPD.map((item) {
    return { "id_apd": item.id_apd, "jumlah" : item.jumlah };
  }).toList();
print(result);

Upvotes: 5

KuKu
KuKu

Reputation: 7492

I think that because you added list item to map by same key "id_apd".

ex )
<List>
[{id_apd: 2}, {id_apd: 3}, {id_apd: 4}]

<Map>
iteration 1: { id_apd: 2}
iteration 2: { id_apd: 3}
iteration 3: { id_apd: 4}

Upvotes: 1

Related Questions