Reputation: 37
I am trying to fetch google book search api data. https://www.googleapis.com/books/v1/volumes?q=%EA%B2%BD%EC%A0%9C
I followed this one: https://docs.flutter.dev/cookbook/networking/fetch-data
My class:
class Book {
final String id;
final String title;
final List<String> authors;
const Book({
required this.id,
required this.title,
required this.authors,
});
factory Book.fromJson(Map json) {
return Book(
id: json['id'],
title: json['title'],
authors: json['author'],
);
}
}
request data:
late Future<List<Book>> futureBooks;
Future<List<Book>> fetchBooks() async {
Uri url = Uri.parse(
'https://www.googleapis.com/books/v1/volumes?q=경제 경영'); //&maxResults=1
final response = await http.get(url);
if (response.statusCode == 200) {
var json = jsonDecode(response.body);
List<dynamic> items = json['items'];
List<Book> books = (items.map((item) {
return Book.fromJson(item);
})).toList();
return books;
} else {
throw Exception('Failed to load Books');
}
}
@override
void initState() {
super.initState();
futureBooks = fetchBooks();
}
I think I have same issue with this. How to solve the "Type Null is not a subtype of type ..." error?
So I appended [?] for fields.
class Book {
final String? id;
final String? title;
final List<String>? authors;
It still give me null.
how to get data?
Upvotes: 0
Views: 81
Reputation: 3455
because title
and author
is not inside item
object, it inside volumeInfo
, so you much change fromJson
method of your Book class to
factory Book.fromJson(Map json) {
return Book(
id: json['id'],
title: json['volumeInfo']['title'],
authors: json['volumeInfo']['author'],
);
}
Upvotes: 1