Flutter图书馆API访问插件open_library_api的使用

Flutter图书馆API访问插件open_library_api的使用

简介

open_library_api 是一个用于访问 openlibrary.org API 的 Dart 实现插件。它允许开发者通过 ISBN 查询书籍信息,并支持 10 位和 13 位 ISBN 编号。此外,它还提供了作者、封面等附加信息,并且可以通过 Uint8List 提供封面图片以在 Flutter 中使用。

特性

  • 使用 ISBN 查询书籍信息。
  • 支持 10 和 13 位 ISBN 号。
  • 添加作者和封面到书籍结果对象中。
  • 封面可以轻松在 Flutter 中使用,通过 MemoryImage 提供 Uint8List
  • 按标题、作者、ISBN 或统一查询搜索书籍。
  • 新增按主题、地点、人物、语言和出版社搜索的模式。
  • 支持加载小、中、大尺寸封面或禁用封面加载。

示例应用

示例应用截图

安装

在您的 Flutter 项目的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  open_library: <最新版本>

在您的库中添加以下导入:

import 'package:open_library/open_library.dart';

开始使用

示例代码

import 'package:flutter/material.dart';
import 'package:open_library/open_library.dart';
import 'package:provider/provider.dart';
import 'screens/book_screen.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Provider(
        create: (_) => OpenLibrary(),
        dispose: (_, OpenLibrary service) => service.dispose(),
        child: MaterialApp(
          title: 'Book Example',
          home: BookScreen()
        ));
  }
}

import 'package:flutter/material.dart';
import 'package:open_library/models/ol_book_model.dart';
import 'package:open_library/models/ol_search_model.dart';
import 'package:open_library/open_library.dart';
import 'package:provider/provider.dart';

const ISBN1 = '9783608980806';
const ISBN2 = '0674995171';
const ISBN3 = '3596191130';

class BookScreen extends StatefulWidget {
  BookScreen({Key? key}) : super(key: key);

  final List<OLBook> books = [];

  [@override](/user/override)
  State<BookScreen> createState() => _BookScreenState();
}

class _BookScreenState extends State<BookScreen> {
  final TextEditingController controller = TextEditingController(text: "Lord of the Rings");
  late bool isLoading = false;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blueGrey,
      body: !isLoading
          ? Column(
              children: [
                const SizedBox(height: 50.0),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: MediaQuery.of(context).size.width * 0.6,
                      height: 60.0,
                      child: TextField(
                        controller: controller,
                        cursorColor: Colors.white,
                        style: const TextStyle(color: Colors.white),
                        decoration: const InputDecoration(
                          label: Text("Book title:"),
                          labelStyle: TextStyle(color: Colors.white),
                          focusColor: Colors.white,
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 10.0),
                      child: GestureDetector(
                        onTap: () async {
                          setState(() {
                            isLoading = true;
                          });
                          final OLSearchBase search =
                              await Provider.of<OpenLibrary>(context, listen: false)
                                  .query(q: controller.text, limit: 4);
                          if (search is OLSearch) {
                              widget.books.clear();
                              print("search:\n$search");
                              for (var doc in search.docs) {
                                final OLBook book = OLBook(
                                  title: doc.title,
                                  authors: doc.authors,
                                  covers: doc.covers,
                                );
                                widget.books.add(book);
                              }
                          }
                          setState(() {
                            isLoading = false;
                          });
                        },
                        child: const Icon(
                          Icons.search,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(
                  height: 20.0,
                ),
                const Center(
                    child: Text(
                      "press action button to search for those ISBN's",
                      style: TextStyle(color: Colors.white),
                    )),
                const SizedBox(
                  height: 20.0,
                ),
                const Center(
                    child: Text(
                  "ISBN1:$ISBN1",
                  style: TextStyle(color: Colors.white),
                )),
                const SizedBox(height: 20.0),
                const Center(
                    child: Text(
                  "ISBN2:$ISBN2",
                  style: TextStyle(color: Colors.white),
                )),
                const SizedBox(height: 20.0),
                const Center(
                    child: Text(
                  "ISBN3:$ISBN3",
                  style: TextStyle(color: Colors.white),
                )),
                const SizedBox(height: 20.0),
                SingleChildScrollView(
                  child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: widget.books.length,
                    itemBuilder: (context, index) {
                      return bookWidget(
                          book: widget.books[index], context: context);
                    },
                  ),
                )
              ],
            )
          : const Center(child: CircularProgressIndicator(color: Colors.white,)),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          setState(() {
            isLoading = true;
          });
          widget.books.clear();
          const bool loadCovers = true;
          const CoverSize size = CoverSize.S;
          final OLBookBase book1 =
              await Provider.of<OpenLibrary>(context, listen: false)
                  .getBookByISBN(
                      isbn: ISBN1, loadCover: loadCovers, coverSize: size);
          print(book1.toString());
          if (book1 is OLBook) {
            widget.books.add(book1);
          }
          final OLBookBase book2 =
              await Provider.of<OpenLibrary>(context, listen: false)
                  .getBookByISBN(
                      isbn: ISBN2, loadCover: loadCovers, coverSize: size);
          print(book2.toString());
          if (book2 is OLBook) {
            widget.books.add(book2);
          }
          final OLBookBase book3 =
              await Provider.of<OpenLibrary>(context, listen: false)
                  .getBookByISBN(
                      isbn: ISBN3, loadCover: loadCovers, coverSize: size);
          print(book3.toString());
          if (book3 is OLBook) {
            widget.books.add(book3);
          }
          setState(() {
            isLoading = false;
          });
        },
        child: const Icon(Icons.book),
      ),
    );
  }

  Widget bookWidget({required OLBook book, required BuildContext context}) {
    String author = '';
    if (book.authors.isNotEmpty) {
      author = book.authors.first.name.trim();
    }
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Container(
        width: MediaQuery.of(context).size.width * 0.8,
        height: 80.0,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10.0),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding:
                      const EdgeInsets.only(top: 4.0, bottom: 4.0, left: 20.0),
                  child: SizedBox(
                    width: MediaQuery.of(context).size.width * 0.6,
                    child: Text(
                      book.title,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(
                          color: Colors.black,
                          fontSize: 14,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                ),
                Padding(
                  padding:
                      const EdgeInsets.only(top: 4.0, bottom: 4.0, left: 20.0),
                  child: Text(
                    author,
                    style: const TextStyle(color: Colors.black, fontSize: 12),
                  ),
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.only(right: 20.0),
              child: SizedBox(
                height: book.covers.isNotEmpty ? 64.0 : 0,
                child: book.covers.isNotEmpty
                    ? Image.memory(book.covers.first)
                    : null,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter图书馆API访问插件open_library_api的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter图书馆API访问插件open_library_api的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


open_library_api 是一个用于在 Flutter 应用中访问 Open Library API 的插件。Open Library 是一个开放的、可编辑的图书馆目录,提供了丰富的图书信息、作者信息等。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 open_library_api 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  open_library_api: ^1.0.0 # 请检查最新版本

然后运行 flutter pub get 来安装依赖。

2. 导入包

在你的 Dart 文件中导入 open_library_api 包:

import 'package:open_library_api/open_library_api.dart';

3. 使用插件

接下来,你可以使用 OpenLibraryApi 类来访问 Open Library 的 API。

3.1 获取图书信息

你可以通过 ISBN 或其他标识符获取图书的详细信息。

void fetchBookDetails() async {
  final openLibraryApi = OpenLibraryApi();

  try {
    final book = await openLibraryApi.getBookDetails(isbn: '9780140328721');
    print('Book Title: ${book.title}');
    print('Author(s): ${book.authors.join(', ')}');
    print('Publish Year: ${book.publishYear}');
  } catch (e) {
    print('Error fetching book details: $e');
  }
}

3.2 搜索图书

你可以通过关键词搜索图书。

void searchBooks() async {
  final openLibraryApi = OpenLibraryApi();

  try {
    final results = await openLibraryApi.searchBooks(query: 'Flutter', limit: 5);
    for (var book in results) {
      print('Book Title: ${book.title}');
      print('Author(s): ${book.authors.join(', ')}');
    }
  } catch (e) {
    print('Error searching books: $e');
  }
}

3.3 获取作者信息

你可以通过作者 ID 获取作者的详细信息。

void fetchAuthorDetails() async {
  final openLibraryApi = OpenLibraryApi();

  try {
    final author = await openLibraryApi.getAuthorDetails(authorId: 'OL23919A');
    print('Author Name: ${author.name}');
    print('Bio: ${author.bio}');
  } catch (e) {
    print('Error fetching author details: $e');
  }
}

4. 处理错误

在使用 API 时,可能会遇到网络错误、API 限制等问题。你可以使用 try-catch 来捕获并处理这些错误。

5. 示例代码

以下是一个完整的示例代码,展示如何获取图书信息、搜索图书和获取作者信息:

import 'package:flutter/material.dart';
import 'package:open_library_api/open_library_api.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Open Library API Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: fetchBookDetails,
                child: Text('Fetch Book Details'),
              ),
              ElevatedButton(
                onPressed: searchBooks,
                child: Text('Search Books'),
              ),
              ElevatedButton(
                onPressed: fetchAuthorDetails,
                child: Text('Fetch Author Details'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void fetchBookDetails() async {
    final openLibraryApi = OpenLibraryApi();

    try {
      final book = await openLibraryApi.getBookDetails(isbn: '9780140328721');
      print('Book Title: ${book.title}');
      print('Author(s): ${book.authors.join(', ')}');
      print('Publish Year: ${book.publishYear}');
    } catch (e) {
      print('Error fetching book details: $e');
    }
  }

  void searchBooks() async {
    final openLibraryApi = OpenLibraryApi();

    try {
      final results = await openLibraryApi.searchBooks(query: 'Flutter', limit: 5);
      for (var book in results) {
        print('Book Title: ${book.title}');
        print('Author(s): ${book.authors.join(', ')}');
      }
    } catch (e) {
      print('Error searching books: $e');
    }
  }

  void fetchAuthorDetails() async {
    final openLibraryApi = OpenLibraryApi();

    try {
      final author = await openLibraryApi.getAuthorDetails(authorId: 'OL23919A');
      print('Author Name: ${author.name}');
      print('Bio: ${author.bio}');
    } catch (e) {
      print('Error fetching author details: $e');
    }
  }
}
回到顶部