【问题标题】:Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'未处理的异常:类型 'List<dynamic>' 不是类型 'Map<dynamic, dynamic>' 的子类型
【发布时间】:2022-01-11 09:41:07
【问题描述】:

我目前正在构建一个应用程序来通过 api 读取数据,并且我正在尝试从 JSON Placeholder 解析 JSON api,并且我不断收到 abpve 错误,以防有人知道我非常感谢它。

这是应用程序的模型

class MachineModel {
  int id;
  String machine_name;
  String machine_number_plate;
  double location_lat;
  double location_lng;
  MachineModel({
    int id,
    String machine_name,
    String machine_number_plate,
    double location_lat,
    double location_lng,
  }) {
    this.id = id;
    this.machine_name = machine_name;
    this.machine_number_plate = machine_number_plate;
    this.location_lat = location_lat;
    this.location_lng = location_lng;
  }

  MachineModel.fromJson(Map<String, dynamic> json) {
    this.id = json['id'];
    this.machine_name = json['machine_name'];
    this.machine_number_plate = json['machine_number_plate'];
    this.location_lat = json['location_lat'];
    this.location_lng = json['location_lon'];
  }

  Map<String, dynamic> toJson() => {
        'id': this.id,
        'machine_name': this.machine_name,
        'machine_number_plate': this.machine_number_plate,
        'location_lat': this.location_lat,
        'location_lon': this.location_lng
      };
}

这是应用程序的回购

class MachineRepo {
  final DioClient dioClient;

  MachineRepo({@required this.dioClient});

  Future<ApiResponse> getMachines() async {
    try {
      Response response = await dioClient.get(
        AppConstants.GET_MACHINE_LIST_WAILON,
      );

      return ApiResponse.withSuccess(response);
    } catch (e) {
      return ApiResponse.withError(ApiErrorHandler.getMessage(e));
    }
  }

这是应用程序的提供者

class MachineProvider with ChangeNotifier {
  final MachineRepo machineRepo;
  MachineProvider({@required this.machineRepo});
  bool _isLoading = false;
  List<MachineModel> machines = [];
  List<MachineModel> machines_ = [];
  bool get isLoading => _isLoading;
  Future getMachines() async {
    _isLoading = true;
    ApiResponse apiResponse = await machineRepo.getMachines();
    print(apiResponse);
    _isLoading = false;
    if (apiResponse.response != null &&
        apiResponse.response.statusCode == 200) {
      Map map_ = apiResponse.response.data;
      //TODO: convert API response to MachineModal List
      machines = map_['machines']
          .map<MachineModel>((machine) => MachineModel.fromJson(machine))
          .toList();
      machines_ = machines;
      print(machines);
      notifyListeners();
    } else {
      String errorMessage;
      if (apiResponse.error is String) {
        print(apiResponse.error.toString());
        errorMessage = apiResponse.error.toString();
      } else {
        ErrorResponse errorResponse = apiResponse.error;
        print(errorResponse.errors[0].message);
        errorMessage = errorResponse.errors[0].message;
      }
      notifyListeners();
    }
  }

json

[
    {
        "id": 34406000,
        "machine_name": "Bomag race care .",
        "machine_number_plate": "",
        "location_lat": 0.922445,
        "location_lon": 34.313638
    },
    {
        "id": 244218282,
        "machine_name": "Bus test",
        "machine_number_plate": "",
        "location_lat": -0.883203,
        "location_lon": 50.66626
    },
    {
        "id": 24444459,
        "machine_name": "Test Car",
        "machine_number_plate": "",
        "location_lat": 0.2441445,
        "location_lon": 32.577147
    }
]

任何帮助

【问题讨论】:

  • 请提供您的错误回溯

标签: flutter dart


【解决方案1】:

根据错误所说,您必须将List&lt;dynamic&gt; 转换为Map&lt;dynamic,dynamic&gt;

您可以参考以下示例将地图转换为列表和列表到地图

假设我们有一个这样的模型类。

class Customer {
  String name;
  int age;

  Customer(this.name, this.age);

  @override
  String toString() {
    return '{ ${this.name}, ${this.age} }';
  }
}

我们要做的是将List&lt;Customer&gt; 转换为 Map,反之亦然,如下所示。

 - key: Customer’s name
 - value: Customer’s age
// List of Customers
[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]

// Map { name:age }
{Jack: 23, Adam: 27, Katherin: 25}

让我们进入下一节。

在 Dart/Flutter 中将 Map 转换为 List

让我们先初始化一个 Dart Map。

Map map = {'Jack': 23, 'Adam': 27, 'Katherin': 25};

我们会将此 Map 转换为 List&lt;Customer&gt;,其中 Customer.name 来自键,Customer.age 来自值。

在此之前,先初始化一个空列表。

var list = [];

使用 Map forEach() 方法

现在我们使用 forEach() 方法将我们的 Map 转换为上面的 List。

map.forEach((k, v) => list.add(Customer(k, v)));
print(list);

在上面的代码中,我们从每个键值对创建一个新的 Customer 对象,然后将该对象添加到列表中。

输出:

[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]

使用可迭代的 forEach() 方法

我们也可以使用 Iterable forEach() 方法将 Dart Map 转换为 List。

map.entries.forEach((e) => list.add(Customer(e.key, e.value)));
print(list);

我们将 forEach() 应用于地图的条目属性。

每个条目都有一个键值字段,我们使用它们来创建一个新的客户对象并添加到列表中。

输出:

[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]

使用可迭代的 map() 方法

另一种将 Map 转换为 Dart List 的方法是使用 Iterable map() 方法。

list = map.entries.map((e) => Customer(e.key, e.value)).toList();
print(list);

Map的每一个entry项都会映射到一个Customer对象,entry.key为customer.name,entry.value为customer.age。 然后我们使用 toList() 方法将 Iterable 结果转换为 List。

输出:

[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]

在 Dart/Flutter 中将列表转换为地图 在开始工作之前,我们创建了一个包含一些项目的列表。

List list = [];
list.add(Customer('Jack', 23));
list.add(Customer('Adam', 27));
list.add(Customer('Katherin', 25));

使用 Map.fromIterable()

我们使用fromIterable() 构造函数将List&lt;Customer&gt; 转换为Map。

var map1 = Map.fromIterable(list, key: (e) => e.name, value: (e) => e.age);
print(map1);

我们将 list 作为第一个参数的 Iterable 传递。

然后,对于可迭代的每个元素,该方法分别计算键和值。

输出:

{Jack: 23, Adam: 27, Katherin: 25}

使用可迭代的 forEach() 方法 我们可以通过另一种方式将 Dart List 转换为 Map:forEach() 方法。

var map2 = {};
list.forEach((customer) => map2[customer.name] = customer.age);
print(map2);

这个方法很容易理解。 我们遍历列表,为列表中的每个项目添加一个条目 (key,value) 到 Map。

输出:

{Jack: 23, Adam: 27, Katherin: 25}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-03
    • 2020-05-24
    • 2019-09-26
    • 2021-05-21
    • 1970-01-01
    • 2020-11-05
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多