From 9fe54bfcd14fc66127621aabc32d8a0fd464f83e Mon Sep 17 00:00:00 2001 From: Mirza Widihananta Date: Fri, 10 Nov 2023 19:14:20 +0700 Subject: [PATCH] fix: infinite loading when we load pdf preview for the first time --- .../presentation/pages/pdf_viewer_page.dart | 59 ++++++++++++++----- 1 file changed, 43 insertions(+), 16 deletions(-) diff --git a/app/lib/features/material/viewer/presentation/pages/pdf_viewer_page.dart b/app/lib/features/material/viewer/presentation/pages/pdf_viewer_page.dart index eb3055f..f338ab9 100644 --- a/app/lib/features/material/viewer/presentation/pages/pdf_viewer_page.dart +++ b/app/lib/features/material/viewer/presentation/pages/pdf_viewer_page.dart @@ -25,14 +25,22 @@ class _PdfViewerPageState extends State { @override void initState() { super.initState(); - if (File('$basePath${widget.id}.pdf').existsSync()) { + initializePdf(); + } + + Future initializePdf() async { + final file = File('$basePath${widget.id}.pdf'); + // ignore: avoid_slow_async_io + if (await file.exists()) { setState(() { - localPathPdf = '$basePath${widget.id}.pdf'; + localPathPdf = file.path; }); } - WidgetsBinding.instance.addPostFrameCallback((_) { - fetchUrlPdfFile(widget.pdfUrl.toString()); - }); + } + + @override + void dispose() { + super.dispose(); } @override @@ -55,22 +63,41 @@ class _PdfViewerPageState extends State { ), body: Stack( children: [ - localPathPdf == '' - ? const LinearProgressIndicator() - : PDFView( - filePath: localPathPdf, - onError: (error) { - // Do Nothing - }, - onPageError: (page, error) { - // Do Nothing - }, - ), + FutureBuilder( + future: _loadPdf(), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.done) { + if (snapshot.hasError) { + return const Center(child: Text('Error loading PDF')); + } else { + return PDFView( + filePath: localPathPdf, + onError: (error) { + // Handle PDF view error + }, + onPageError: (page, error) { + // Handle PDF view error on a specific page + }, + ); + } + } else { + return const Center(child: CircularProgressIndicator()); + } + }, + ), ], ), ); } + Future _loadPdf() async { + if (localPathPdf == '') { + await fetchUrlPdfFile(widget.pdfUrl.toString()); + } + // Return a Future to satisfy the FutureBuilder + return Future.value(); + } + // Pdf Print Future _generatePdf() async { try {