每当我尝试获取数据时,都会引发异常:
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The method 'map' was called on null.
Receiver: null
Tried calling: map<Location>(Closure: (dynamic) => Location))
print(responses)
在控制台上打印null
。
这是我从api获取响应的功能:
String url1 = 'http://192.168.43.171:3000/location';
Future<void> showLocation() async {
var response = await http.get(Uri.encodeFull(url1));
if (response.statusCode == 200) {
print(response.body);
// Map<String, dynamic> parsedMap=jsonDecode(response.body);
final data = json.decode(response.body);
final responses = Details.fromJson(data[0]);
print(responses);
// print(parsedMap['location']);
} else {
throw Exception('failed to load');
}
}
这是我的locationModel.dart:
class Location {
final String latitude;
final String longitude;
Location({this.latitude, this.longitude});
factory Location.fromJson(Map<String, dynamic> parsedJson) {
return Location(
latitude: parsedJson['latitude'], longitude: parsedJson['longitude']);
}
}
class Details {
final String username;
final List<Location> locations;
Details({this.username, this.locations});
factory Details.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['locations'] as List;
print(list.runtimeType);
List<Location> locationList =
list.map((i) => Location.fromJson(i)).toList();
return Details(username: parsedJson['username'], locations: locationList);
}
}
我的JSON:
[
{
"id":"ABC",
"username":"xyz",
"location":[
{
"latitude": "34",
"longitude": "343"
},
{
"latitude": "34",
"longitude": "32"
}
]
}
{
"id":"ABC1",
"username":"xyz1",
"location":[
{
"latitude": "34222",
"longitude": "32243"
},
]
}
]
答案 0 :(得分:0)
您有错字:
var list = parsedJson['locations'] as List;
vs
location:[
位置!=位置