First, create a Photo class that contains data about a photo. Include a fromJson() factory method to make it easy to create a Photo starting with a JSON object.
class Photo {
final int id;
final String title;
final String thumbnailUrl;
Photo({this.id, this.title, this.thumbnailUrl});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
id: json[‘id‘] as int,
title: json[‘title‘] as String,
thumbnailUrl: json[‘thumbnailUrl‘] as String,
);
}
}
Now, use the following instructions to update the fetchPhotos() function so that it returns a Future<List<Photo>>:
parsePhotos() function that converts the response body into a List<Photo>.parsePhotos() function in the fetchPhotos() function.// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response =
await client.get(‘https://jsonplaceholder.typicode.com/photos‘);
return parsePhotos(response.body);
}
原文:https://www.cnblogs.com/sendling/p/13198824.html