Why I'm getting this exception: _TypeError (type 'List' is not a subtype of type 'Map<String, dynamic>')
this is my http method:
import 'dart:convert';
import 'package:arzenafees/model/areaguide.dart';
import 'package:http/http.dart' as http;
Future<Areaguide> fetcharea() async {
final response = await http.get(
Uri.parse('https://arz-e-nafees.nafeessolutions.com/public/api/view'));
if (response.statusCode == 200) {
return Areaguide.fromJson(jsonDecode(response.body));
} else {
throw Exception('Unexpected error occured!');
}
}
this is my model class which I created using quicktype.io:
import 'dart:convert';
List<Areaguide> areaguideFromJson(String str) =>
List<Areaguide>.from(json.decode(str).map((x) => Areaguide.fromJson(x)));
String areaguideToJson(List<Areaguide> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Areaguide {
Areaguide({
required this.propertyImage,
required this.propertyTitle,
required this.locationCity,
required this.locationArea,
required this.propertyDescription,
required this.propertyPrice,
});
String propertyImage;
String propertyTitle;
String locationCity;
String locationArea;
String propertyDescription;
String propertyPrice;
factory Areaguide.fromJson(Map<String, dynamic> json) => Areaguide(
propertyImage: json["property_image"],
propertyTitle: json["property_title"],
locationCity: json["location_city"],
locationArea: json["location_area"],
propertyDescription: json["property_description"],
propertyPrice: json["property_price"],
);
Map<String, dynamic> toJson() => {
"property_image": propertyImage,
"property_title": propertyTitle,
"location_city": locationCity,
"location_area": locationArea,
"property_description": propertyDescription,
"property_price": propertyPrice,
};
}
Note: please provide answer which applies to all related question, do not limits it to this specific problem, which might help others with type errors.
CodePudding user response:
Try this.
static Future<List<Areaguide>?> fetcharea() async {
final response = await http.get(
Uri.parse('https://arz-e-nafees.nafeessolutions.com/public/api/view));
if (response.statusCode == 200) {
List<Areaguide> property = (json.decode(response.body)).map<Areaguide>((m)=> Areaguide.fromJson(m)).toList();
return property;
} else {
throw Exception('Unexpected error occured!');
}
}
CodePudding user response:
Instead of writing fromJson and toJson methods, you can use json_serializable library (https://docs.flutter.dev/development/data-and-backend/json). In short: after installing the dependency you just define your model and run a command. It works also for nested models.