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';

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

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

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())),
)

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())),
           )
          )
      );
  }
}

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

No any Comments on this Article


Please Wait...