打印出所有的 hashMap 值

Print out all hashMap value

想知道如果需要用 dart 语言编写,我如何循环遍历级别列表以获取所有项目?

  var headers = {
    'authorization': "Bearer" + " " + accessToken,
    "Accept": "application/json"
  };
  var url =
      'https://xxx';
  var response = await http.get(url, headers: headers);
  var res = DataResponse.fromJson(json.decode(response.body));

  for(var i in res.levels){
       ....  // I want print out the three items
  }

数据响应

part 'data_response.g.dart';

    @JsonSerializable()
    class RFWIMasterDataResponse extends BaseResponse {
      var levels = List<Level>();
    
      DataResponse();
    
      factory DataResponse.fromJson(Map<String, dynamic> json) =>
          _$RFWIMasterDataResponseFromJson(json);
      Map<String, dynamic> toJson() => _$DataResponseToJson(this);
    }

这里是Json输出

"levels":[
   {
      "3":{
         "id":"3",
         "level_no":"3"
      },
      "2":{
         "id":"2",
         "level_no":"2"
      },
      "1":{
         "id":"1",
         "level_no":"1"
      }
   }
]

一般来说,除了嵌套地图之外别无其他。看到这个 .

但是,在我为你的案例准备了一个测试。

import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';

void main() {
  final String stringMap =
      '{"levels":[{"3":{"id":"3","level_no":"3"},"2":{"id":"2","level_no":"2"},"1":{"id":"1","level_no":"1"}}]}';

  test("should have nested map on decode", () {
    final map = json.decode(stringMap);
    expect(map, isA<Map<dynamic, dynamic>>());
    //levels is a list
    expect(map["levels"], isA<List>());
    //get the map if the list
    expect(map["levels"][0], isA<Map<dynamic, dynamic>>());
    map["levels"][0].forEach((key, value) {
      print("key is 3 -> $key");
      //get values by named index
      print("values are ${value["id"]} and ${value["level_no"]}");
      //you can also iterate over the values->values
      value.forEach((innerKey, innerValue) {
        //do something
      });
    });
  });
}