flutter_pdfview 显示服务端的pdf文件

姜旭
2023-12-01

需要先将pdf文件下载下来后,再显示。

import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:path_provider/path_provider.dart';
import 'package:dio/dio.dart';
import 'package:flutter_mj/util/navigator_util.dart';

class PDFScreen extends StatefulWidget {
  final String path;

  PDFScreen({Key key, this.path}) : super(key: key);

  _PDFScreenState createState() => _PDFScreenState();
}

class _PDFScreenState extends State<PDFScreen> with WidgetsBindingObserver {
  final Completer<PDFViewController> _controller = Completer<PDFViewController>();
  int pages = 0;
  int currentPage = 0;
  bool isReady = false;
  String errorMessage = '';
  String pdfFilePath = '';

  ///当前进度进度百分比  当前进度/总进度 从0-1
  double currentProgress = 0.0;

  ///下载文件的网络路径
  String apkUrl = "";

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

    if (widget.path.startsWith('http')) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        //downApkFunction();
      });
    } else {
      pdfFilePath = widget.path;
    }
  }

  ///使用dio 下载文件
  Future<String> downApkFunction() async {
    {
      ///手机储存目录
      final directory = await getTemporaryDirectory();
      String savePath = directory.path;
      //FIXME: 需要生成随记文件名
      String appName = "temp.pdf";
      String fileFullPath = "${savePath}/${appName}";
      print('===========fileFullPath:$fileFullPath');
      Dio dio = Dio();
      await dio.download(widget.path, fileFullPath);

      return fileFullPath;
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget pdfView;
    if (widget.path.startsWith('http')) {
      pdfView = FutureBuilder<String>(
        future: downApkFunction(),
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          if (snapshot.hasData) {
            String response = snapshot.data;
            return _buildPdfView(response);
          }
          return Container();
        },
      );
    } else {
      pdfView = _buildPdfView(widget.path);
    }

    return Scaffold(
      appBar: NavigatorUtil.appbar('简历', elevation: 0),
      body: Stack(
        children: [
          pdfView,
          errorMessage.isEmpty
              ? !isReady
                  ? Center(
                      child: CircularProgressIndicator(),
                    )
                  : Container()
              : Center(
                  child: Text(errorMessage),
                )
        ],
      ),
      floatingActionButton: FutureBuilder<PDFViewController>(
        future: _controller.future,
        builder: (context, AsyncSnapshot<PDFViewController> snapshot) {
          if (snapshot.hasData) {
            return FloatingActionButton.extended(
              label: Text("Go to ${pages ~/ 2}"),
              onPressed: () async {
                await snapshot.data.setPage(pages ~/ 2);
              },
            );
          }

          return Container();
        },
      ),
    );
  }

  Widget _buildPdfView(String pdfFilePath) {
    return PDFView(
      filePath: pdfFilePath,
      enableSwipe: true,
      swipeHorizontal: true,
      autoSpacing: false,
      pageFling: true,
      pageSnap: true,
      defaultPage: currentPage,
      fitPolicy: FitPolicy.BOTH,
      preventLinkNavigation: false,
      // if set to true the link is handled in flutter
      onRender: (_pages) {
        setState(() {
          pages = _pages;
          isReady = true;
        });
      },
      onError: (error) {
        setState(() {
          errorMessage = error.toString();
        });
        print(error.toString());
      },
      onPageError: (page, error) {
        setState(() {
          errorMessage = '$page: ${error.toString()}';
        });
        print('$page: ${error.toString()}');
      },
      onViewCreated: (PDFViewController pdfViewController) {
        _controller.complete(pdfViewController);
      },
      onLinkHandler: (String uri) {
        print('goto uri: $uri');
      },
      onPageChanged: (int page, int total) {
        print('page change: $page/$total');
        setState(() {
          currentPage = page;
        });
      },
    );
  }
}
 类似资料: