queryBooks function

Future<List<Book>> queryBooks(
  1. String query, {
  2. QueryType? queryType,
  3. String? langRestrict,
  4. int maxResults = 10,
  5. OrderBy? orderBy,
  6. PrintType? printType = PrintType.all,
  7. int startIndex = 0,
  8. bool reschemeImageLinks = false,
})

Query a list of books

query parameter must not be null and must not be empty. Spaces characters are allowed

Set queryType to specify the search by a specific keyword

Set langRestrict to restrict the query to a specific language

Set orderBy to order the query by newest or relevance and printType to filter in books or magazines

Set maxResults to set the max amount of results. Set startIndex for pagination

Example of querying:

void main(List<String> args) async {
  final books = await queryBooks(
    'twilight',
    maxResults: 3,
    printType: PrintType.books,
    orderBy: OrderBy.relevance,
  );
  books.forEach((Book book) {
    print(book);
  });
}

Implementation

Future<List<Book>> queryBooks(
  String query, {
  QueryType? queryType,
  String? langRestrict,
  int maxResults = 10,
  OrderBy? orderBy,
  PrintType? printType = PrintType.all,
  int startIndex = 0,
  bool reschemeImageLinks = false,
}) async {
  assert(query.isNotEmpty);

  // assert(startIndex <= maxResults);

  var url = 'https://www.googleapis.com/books/v1/volumes?q=';

  if (queryType != null) url += queryType.name + ':';

  var q = '$url'
      '${query.trim().replaceAll(' ', '+')}'
      '&maxResults=$maxResults'
      '&startIndex=$startIndex';

  if (langRestrict != null) q += '&langRestrict=$langRestrict';
  if (orderBy != null) {
    q += '&orderBy=${orderBy.toString().replaceAll('OrderBy.', '')}';
  }
  if (printType != null) {
    q += '&printType=${printType.toString().replaceAll('PrintType.', '')}';
  }
  final result = await http.get(Uri.parse(q));
  if (result.statusCode == 200) {
    final books = <Book>[];
    final list = (jsonDecode(result.body))['items'] as List<dynamic>?;
    if (list == null) return [];
    for (final e in list) {
      books.add(Book.fromJson(e, reschemeImageLinks: reschemeImageLinks));
    }
    return books;
  } else {
    throw (result.body);
  }
}