Flutter电子书阅读插件lentera_epub_viewer的使用

Flutter电子书阅读插件lentera_epub_viewer的使用

lentera_epub_viewer 是一个用于在 Flutter 应用程序中显示 EPUB 文件的插件。它封装了 folioreader 框架,并支持 iOS 和 Android 平台。

特性

功能名称 Android iOS
阅读进度(剩余时间/页数)
最后读取位置
免打扰阅读模式
从资源加载 EPUB
复制和分享文本
文本高亮
多主题(浅色/深色)
支持多设备语言
更改字体样式
支持 Android 13

截图

浅色模式

Light Mode Screenshot Light Mode Screenshot Light Mode Screenshot Light Mode Screenshot Light Mode Screenshot Light Mode Screenshot

深色模式

Dark Mode Screenshot Dark Mode Screenshot Dark Mode Screenshot Dark Mode Screenshot Dark Mode Screenshot

安装

要使用该插件,首先确保你的项目配置正确。在 iOS 上,你需要安装 Swift,并且最低部署目标为 9.0。

pubspec.yaml 文件中添加依赖:

dependencies:
  lentera_epub_viewer: latest_version

注意:请在 Android 的发布构建类型中添加以下代码以避免发布版本崩溃:

minifyEnabled false
shrinkResources false

AndroidManifest.xml 中添加必要的权限:

<uses-permission android:name="android.permission.INTERNET" />
<application
    xmlns:tools="http://schemas.android.com/tools"
    android:usesCleartextTraffic="true"
    android:requestLegacyExternalStorage="true"
    android:networkSecurityConfig="@xml/network_security_config"
    android:exported="true">
</application>

android/app/src/main/res/xml 目录下创建 network_security_config.xml 文件,并添加以下内容:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">your_domain.com</domain>
    </domain-config>
</network-security-config>

使用

在 Dart 代码中,你可以使用以下方法来初始化和打开 EPUB 文件:

import 'package:lentera_epub_viewer/epub_viewer.dart';

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool loading = false;
  String filePath = "";

  [@override](/user/override)
  void initState() {
    download();
    super.initState();
  }

  download() async {
    // 下载 EPUB 文件
    Directory? appDocDir = await getExternalStorageDirectory();
    String path = appDocDir!.path + '/sample.epub';
    File file = File(path);

    if (!file.existsSync()) {
      await file.create();
      await dio.download(
        "https://vocsyinfotech.in/envato/cc/flutter_ebook/uploads/22566_The-Racketeer---John-Grisham.epub",
        path,
        deleteOnError: true,
        onReceiveProgress: (receivedBytes, totalBytes) {
          setState(() {
            loading = true;
          });
        },
      ).whenComplete(() {
        setState(() {
          loading = false;
          filePath = path;
        });
      });
    } else {
      setState(() {
        loading = false;
        filePath = path;
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('EPUB Reader Example'),
        ),
        body: Center(
          child: loading
              ? Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(),
                    Text('Downloading.... E-pub'),
                  ],
                )
              : Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () async {
                        if (filePath == "") {
                          download();
                        } else {
                          EpubViewer.setConfig(
                            themeColor: Theme.of(context).primaryColor,
                            identifier: "iosBook",
                            scrollDirection: EpubScrollDirection.ALLDIRECTIONS,
                            allowSharing: false,
                            enableTts: true,
                            nightMode: true,
                          );

                          // 获取当前读取位置
                          EpubViewer.locatorStream.listen((locator) {
                            print('LOCATOR: $locator');
                          });

                          EpubViewer.open(
                            filePath,
                            lastLocation: EpubLocator.fromJson({
                              "bookId": "2239",
                              "href": "/OEBPS/ch06.xhtml",
                              "created": 1539934158390,
                              "locations": {"cfi": "epubcfi(/0!/4/4[simple_book]/2/2/6)"}
                            }),
                          );
                        }
                      },
                      child: Text('Open Downloaded E-pub'),
                    ),
                    ElevatedButton(
                      onPressed: () async {
                        EpubViewer.setConfig(
                          themeColor: Theme.of(context).primaryColor,
                          identifier: "iosBook",
                          scrollDirection: EpubScrollDirection.ALLDIRECTIONS,
                          allowSharing: false,
                          enableTts: true,
                          nightMode: true,
                        );

                        // 获取当前读取位置
                        EpubViewer.locatorStream.listen((locator) {
                          print('LOCATOR: $locator');
                        });

                        await EpubViewer.openAsset(
                          'assets/4.epub',
                          lastLocation: EpubLocator.fromJson({
                            "bookId": "2239",
                            "href": "/OEBPS/ch06.xhtml",
                            "created": 1539934158390,
                            "locations": {"cfi": "epubcfi(/0!/4/4[simple_book]/2/2/6)"}
                          }),
                        );
                      },
                      child: Text('Open Assets E-pub'),
                    ),
                  ],
                ),
        ),
      ),
    );
  }
}

更多关于Flutter电子书阅读插件lentera_epub_viewer的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter电子书阅读插件lentera_epub_viewer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


lentera_epub_viewer 是一个用于在 Flutter 应用中显示 EPUB 电子书的插件。它提供了简单的 API,可以轻松地将 EPUB 文件加载到应用中,并支持基本的阅读功能,如翻页、缩放、书签等。

安装

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

dependencies:
  flutter:
    sdk: flutter
  lentera_epub_viewer: ^1.0.0  # 使用最新版本

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

基本用法

  1. 导入包

    import 'package:lentera_epub_viewer/lentera_epub_viewer.dart';
    
  2. 加载并显示 EPUB 文件

    你可以通过 LenteraEpubViewer 来加载并显示 EPUB 文件。以下是一个简单的示例:

    class EpubReaderScreen extends StatelessWidget {
      final String epubPath;
    
      EpubReaderScreen({required this.epubPath});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('EPUB Reader'),
          ),
          body: LenteraEpubViewer(
            filePath: epubPath,
            onViewerLoaded: () {
              print('EPUB 文件加载完成');
            },
            onViewerError: (error) {
              print('EPUB 文件加载错误: $error');
            },
          ),
        );
      }
    }
    
  3. 处理 EPUB 文件的路径

    通常,EPUB 文件会存储在应用的 assets 文件夹中,或者从网络下载后存储在本地文件系统中。你需要确保传递正确的文件路径给 LenteraEpubViewer

    • assets 加载

      如果你将 EPUB 文件放在 assets 文件夹中,首先需要在 pubspec.yaml 中声明:

      flutter:
        assets:
          - assets/sample.epub
      

      然后在代码中使用 DefaultAssetBundle 来获取文件路径:

      String epubPath = await DefaultAssetBundle.of(context).loadString('assets/sample.epub');
      
    • 从本地文件系统加载

      如果你从网络下载 EPUB 文件并存储在本地文件系统中,可以直接传递文件路径:

      String epubPath = '/path/to/local/sample.epub';
      
  4. 自定义配置

    LenteraEpubViewer 提供了一些可选的参数来配置阅读器的外观和行为,例如:

    • themeColor: 设置主题颜色。
    • initialIndex: 设置初始打开的章节索引。
    • allowSharing: 是否允许分享 EPUB 文件。

    例如:

    LenteraEpubViewer(
      filePath: epubPath,
      themeColor: Colors.blue,
      initialIndex: 0,
      allowSharing: true,
    );
回到顶部