Open Ajaydev4342 opened 1 year 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,
),
);
}
});
I am keep getting ... unexcpected error.