ScerIO / packages.flutter

👨‍💻 Plugins and packages for Flutter framework
https://pub.dev/publishers/serge.software/packages
MIT License
461 stars 454 forks source link

Epub_view issue with opening file keep getting unexpected exception. #390

Open Ajaydev4342 opened 1 year ago

Ajaydev4342 commented 1 year ago

I am keep getting ... unexcpected error.

Screenshot 2023-03-01 at 1 05 24 AM Screenshot 2023-03-01 at 1 06 36 AM
Leboweeb commented 5 months ago

I know this thread is old, but I have found a solution to this problem.

The problem is loading an asset file is asynchronous, but the initState function is now synchronous so by the time you reach the build function, the epub file hasn't even loaded in yet!

Luckily, the fix is very simple. You just make an async function to load the epub asset as bytes and then feed those bytes into the EpubDocument.openData method. After that, you use a FutureBuilder to use the epub controller.

Here are some useful links:

Full Code Example:

  Future<EpubController> loadEpub() async {
    var asset = await PlatformAssetBundle().load("assets/alice.epub");
    return EpubController(
        document: EpubDocument.openData(asset.buffer
            .asUint8List(asset.offsetInBytes, asset.lengthInBytes)));
  }

  @override
  Widget build(BuildContext context) => FutureBuilder<EpubController>(
      future: loadEpub(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Text("Waiting......");
        } else if (snapshot.hasError) {
          return Text("Error : ${snapshot.error}");
        } else {
          var epubController = snapshot.data!;
          return Scaffold(
            appBar: AppBar(
              // Show actual chapter name
              title: EpubViewActualChapter(
                  controller: epubController,
                  builder: (chapterValue) => Text(
                        'Chapter: ${chapterValue?.chapter?.Title?.replaceAll('\n', '').trim() ?? ''}',
                        textAlign: TextAlign.start,
                      )),
            ),
            // Show table of contents
            drawer: Drawer(
              child: EpubViewTableOfContents(
                controller: epubController,
              ),
            ),
            // Show epub document
            body: EpubView(
              controller: epubController,
            ),
          );
        }
      });