Download StackFood Multi Restaurant, Food Delivery App with Laravel Admin and Restaurant Panel Buy Full App on $79
Download FlutKit - Flutter UI Kit Most beautiful Flutter UI Kit with 20+ Full App, 450+ Screens. Buy Full Kit on $39
Download Fluxstore Multi Vendor WooCommerce/Dokan Plugin compatible WordPress eCommerce Flutter App. Buy Full App on $79

How to View PDF from URL with Caching in Flutter

In this Flutter code example, we are going to show the easiest way to display PDF files from URL with caching on Flutter App. You can achieve this feature with the help of a package. See the example below.

See this also: How to list PDF files from Storage and View on Click

First, add flutter_cached_pdfview package in your project by adding the following lines on pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  flutter_cached_pdfview: ^0.3.5

Import package to script:

import 'package:flutter_cached_pdfview/flutter_cached_pdfview.dart';

How to View PDF File on Flutter App:

PDF().cachedFromUrl(
   'https://www.fluttercampus.com/sample.pdf'
)

Set Duration of Cache:

PDF().cachedFromUrl(
  'https://www.fluttercampus.com/sample.pdf',
  maxAgeCacheObject:Duration(days: 30), //duration of cache
)

See Progress Percentage Indicator while loading:

PDF().cachedFromUrl(
  'https://www.fluttercampus.com/sample.pdf',
  maxAgeCacheObject:Duration(days: 30), //duration of cache
  placeholder: (progress) => Center(child: Text('$progress %')),
  errorWidget: (error) => Center(child: Text(error.toString())),
)

Full Code Example:

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

void main() {
  runApp(
    MaterialApp( 
      home: MyApp()
    )
  );
}

class MyApp extends StatefulWidget{
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
          appBar: AppBar(
              title:Text("View PDF with Caching"), //appbar title
              backgroundColor: Colors.redAccent //appbar background color
          ),
          body: Container(
            child: PDF().cachedFromUrl(
             'https://www.fluttercampus.com/sample.pdf',
              maxAgeCacheObject:Duration(days: 30), //duration of cache
              placeholder: (progress) => Center(child: Text('$progress %')),
              errorWidget: (error) => Center(child: Text(error.toString())),
           )
          )
      );
  }
}

Output Screenshot:

In this way, you can show PDF files on Flutter App with Caching.

No any Comments on this Article


Please Wait...