queryBooks function Null safety

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

Query a list of books

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

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, {
  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 q = 'https://www.googleapis.com/books/v1/volumes?q='
      '${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);
  }
}