Visualizzare file PDF in Flutter con flutter_pdfview

Mattepuffo's logo
Visualizzare file PDF in Flutter con flutter_pdfview

Visualizzare file PDF in Flutter con flutter_pdfview

flutter_pdfview è una libreria per Flutter, solo per mobile, che ci consente di leggere file PDF.

In questo articolo vediamo un esempio; prima di tutto caricate un file PDF in assets.

Poi nel pubspec.yaml aggiungiamo questa sezione:

flutter:
  assets:
    - assets/demo.pdf

Poi installiamo due librerie:

flutter pub add flutter_pdfview path_provider

Fatto ciò questo il codice, che io ho testato solo su Android:

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter PDF Viewer',
      theme: ThemeData(primarySwatch: Colors.deepPurple),
      home: const MyHomePage(title: 'Visualizzatore PDF'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String localPath = '';
  bool isReady = false;
  String errorMessage = '';
  int? pages = 0;
  int? currentPage = 0;
  PDFViewController? pdfController;

  @override
  void initState() {
    super.initState();
    preparePdf();
  }

  Future<void> preparePdf() async {
    try {
      final ByteData bytes = await rootBundle.load('assets/demo.pdf');
      final String dir = (await getApplicationDocumentsDirectory()).path;
      final String filePath = '$dir/demo.pdf';
      final File file = File(filePath);

      await file.writeAsBytes(bytes.buffer.asUint8List(), flush: true);
      setState(() {
        localPath = filePath;
      });
    } catch (e) {
      setState(() {
        errorMessage = e.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body:
          localPath.isEmpty
              ? const Center(child: CircularProgressIndicator())
              : Stack(
                children: [
                  PDFView(
                    filePath: localPath,
                    enableSwipe: true,
                    swipeHorizontal: false,
                    autoSpacing: false,
                    pageFling: true,
                    onRender: (_pages) {
                      setState(() {
                        pages = _pages;
                        isReady = true;
                      });
                    },
                    onError: (error) {
                      setState(() {
                        errorMessage = error.toString();
                      });
                    },
                    onPageError: (page, error) {
                      setState(() {
                        errorMessage = 'Errore  $page: ${error.toString()}';
                      });
                    },
                    onViewCreated: (PDFViewController controller) {
                      pdfController = controller;
                    },
                    onPageChanged: (int? page, int? total) {
                      setState(() {
                        currentPage = page;
                      });
                    },
                  ),
                  if (!isReady && errorMessage.isEmpty)
                    const Center(child: CircularProgressIndicator()),
                  if (errorMessage.isNotEmpty)
                    Center(child: Text(errorMessage)),
                ],
              ),
    );
  }
}

Enjoy!


Condividi

1 Commenti

  • Carla

    Il geografo

    09/10/2025

Commentami!