【问题标题】:Flutter Dart : How to convert List to Map with 2 keyFlutter Dart:如何使用 2 个键将 List 转换为 Map
【发布时间】:2020-10-04 11:27:49
【问题描述】:

我在将列表转换为地图时遇到问题,我正在使用map.fromiterable 来转换我的列表,但它只能显示 1 个数据和 1 个键。 这是它的输出:

[{id_apd: 4}]

这是我的班级模型列表,

class APDPengajuanModel {
  final int id_apd;
  final int jumlah;

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

}

这是我将列表转换为地图的函数。

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);
}

从我上面的代码中,它只能显示 id_apd 而不能显示列表中的 jumlah 变量。

请帮助如何同时显示 id_apd 和 jumlah :)

这是我希望的输出,但不是这样显示的。

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

【问题讨论】:

    标签: json list dictionary flutter dart


    【解决方案1】:

    我认为标题的含义与您希望的输出之间存在差异。 这是您希望的结果的代码。

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

    【讨论】:

    • 很抱歉我不能投票,我的声誉在 15 岁以下。但再次感谢
    • 你也可以使用列表文字:dart var result = [for (var item in listAPD) {"id_apd": item.id_apd, "jumlah": item.jumlah}]; print(result);
    • 感谢您的解决方案,我也赞成
    【解决方案2】:

    我假设您有 2 个列表要合并到列表映射中

    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));
    

    结果:

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

    【讨论】:

      【解决方案3】:

      我认为这是因为您通过相同的键“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}
      

      【讨论】:

      • 如何使用 map.fromiterable 设置多个键?
      猜你喜欢
      • 2020-12-18
      • 2020-04-08
      • 1970-01-01
      • 2021-06-07
      • 2017-11-02
      • 2022-01-08
      • 2017-07-14
      • 1970-01-01
      • 2021-07-01
      相关资源
      最近更新 更多