[英]Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
I am currently building an app to read data through an api and I am trying to parse a JSON api from JSON Placeholder and i keep getting the abpve error incase anyone has an idea i highky appreciate it. I am currently building an app to read data through an api and I am trying to parse a JSON api from JSON Placeholder and i keep getting the abpve error incase anyone has an idea i highky appreciate it.
This is the model of the app这是应用程序的 model
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
};
}
This is the Repo of the app这是应用程序的回购
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));
}
}
Ths is the Provider of the app这是应用程序的提供者
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 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
}
]
Any help with this对此有任何帮助
As per error said you have to convert List<dynamic>
to Map<dynamic,dynamic>
根据错误所说,您必须将
List<dynamic>
转换为Map<dynamic,dynamic>
You can refer the below example to Convert Map to List & List to Map您可以参考以下示例将 Map 转换为列表和列表到 Map
Assume that we have a model class like this.假设我们有一个像这样的 model class。
class Customer {
String name;
int age;
Customer(this.name, this.age);
@override
String toString() {
return '{ ${this.name}, ${this.age} }';
}
}
What we'll do is to convert List<Customer>
into Map and vice versa as below.我们要做的是将
List<Customer>
转换为 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}
Let's go to the next sections.让我们 go 到下一节。
Convert Map to List in Dart/Flutter在 Dart/Flutter 中将 Map 转换为 List
Let's initialize a Dart Map first.我们先初始化一个 Dart Map。
Map map = {'Jack': 23, 'Adam': 27, 'Katherin': 25};
We will convert this Map to List<Customer>
with Customer.name from a key and Customer.age from a value.我们将把这个 Map 转换为
List<Customer>
,其中 Customer.name 来自键,Customer.age 来自值。
Before that, initialize an empty list first.在此之前,先初始化一个空列表。
var list = [];
Using Map forEach() method使用 Map forEach() 方法
Now we convert our Map to List above using forEach() method.现在我们使用 forEach() 方法将我们的 Map 转换为上面的列表。
map.forEach((k, v) => list.add(Customer(k, v)));
print(list);
In the code above, we create a new Customer object from each key-value pair, then add the object to the list.在上面的代码中,我们从每个键值对创建一个新的客户 object,然后将 object 添加到列表中。
Output: Output:
[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]
Using Iterable forEach() method使用可迭代的 forEach() 方法
We can also convert a Dart Map to List using Iterable forEach() method instead.我们也可以使用 Iterable forEach() 方法将 Dart Map 转换为 List 。
map.entries.forEach((e) => list.add(Customer(e.key, e.value)));
print(list);
We apply forEach() to entries property of the map.我们将 forEach() 应用于 map 的条目属性。
Every entry has a key-value field, we use them to create a new Customer object and add to the list.每个条目都有一个键值字段,我们使用它们创建一个新的客户 object 并添加到列表中。
Output: Output:
[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]
Using Iterable map() method使用可迭代的 map() 方法
Another way to convert Map to a Dart List is to use Iterable map() method.将 Map 转换为 Dart 列表的另一种方法是使用 Iterable map() 方法。
list = map.entries.map((e) => Customer(e.key, e.value)).toList();
print(list);
Each entry item of Map's entries will be mapped to a Customer object with entry.key as customer.name and entry.value as customer.age. Map的每个entry项都会映射到一个Customer object,entry.key为customer.name,entry.value为customer.age。 Then we convert the Iterable result to List using toList() method.
然后我们使用 toList() 方法将 Iterable 结果转换为 List。
Output: Output:
[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]
Convert List to Map in Dart/Flutter Before doing our work, we create a List with some items.在 Dart/Flutter 中将 List 转换为 Map 在开始工作之前,我们创建一个包含一些项目的 List。
List list = [];
list.add(Customer('Jack', 23));
list.add(Customer('Adam', 27));
list.add(Customer('Katherin', 25));
Using Map.fromIterable()使用 Map.fromIterable()
We convert List<Customer>
into Map using fromIterable()
constructor.我们使用
fromIterable()
构造函数将List<Customer>
转换为 Map 。
var map1 = Map.fromIterable(list, key: (e) => e.name, value: (e) => e.age);
print(map1);
We pass list as an Iterable for the first param.我们将 list 作为第一个参数的 Iterable 传递。
Then, for each element of the iterable, the method computes key and value respectively.然后,对于可迭代的每个元素,该方法分别计算键和值。
Output: Output:
{Jack: 23, Adam: 27, Katherin: 25}
Using Iterable forEach() method We can convert Dart List to Map in another way: forEach() method.使用 Iterable forEach() 方法 我们可以用另一种方式将 Dart List 转换为 Map:forEach() 方法。
var map2 = {};
list.forEach((customer) => map2[customer.name] = customer.age);
print(map2);
This method is simple to understand.这种方法很容易理解。 We iterate over the list, for each item in the list, we add an entry
(key,value)
to the Map.我们遍历列表,对于列表中的每个项目,我们将一个条目
(key,value)
添加到 Map。
Output: Output:
{Jack: 23, Adam: 27, Katherin: 25}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.