You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pdf_viewer_plugin无法加载PDF的Flutter技术问题求助

问题原因分析

从错误日志的FileSource和FileNotFoundException可以看出:pdf_viewer_plugin: ^2.0.0的PdfView组件的path参数仅支持本地文件路径,不直接支持网络URL。直接传入网络链接时,插件会尝试在本地文件系统中查找该路径,自然找不到对应文件,抛出异常。


解决方案

方案一:先下载PDF到本地,再加载本地文件

通过http库下载PDF数据,保存到应用本地目录后,再用本地路径加载。

1. 添加依赖

在pubspec.yaml中添加所需依赖:

dependencies:
  flutter:
    sdk: flutter
  pdf_viewer_plugin: ^2.0.0
  http: ^0.13.5
  path_provider: ^2.0.15

2. 修改Flutter代码

import 'dart:typed_data';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:pdf_viewer_plugin/pdf_viewer_plugin.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';

class PdfShowPage extends StatefulWidget {
  const PdfShowPage({Key? key}) : super(key: key);

  @override
  State<PdfShowPage> createState() => _PdfShowPageState();
}

class _PdfShowPageState extends State<PdfShowPage> {
  String? localPdfPath;
  bool isLoading = true;

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

  Future<void> _downloadPdf() async {
    try {
      // 发起请求下载PDF
      final response = await http.get(Uri.parse('https://10.0.2.2:7272/api/Pdf'));
      if (response.statusCode == 200) {
        // 获取应用临时存储目录
        final directory = await getTemporaryDirectory();
        final localFile = File('${directory.path}/temp_pdf.pdf');
        // 将下载的字节数据写入本地文件
        await localFile.writeAsBytes(response.bodyBytes);
        
        setState(() {
          localPdfPath = localFile.path;
          isLoading = false;
        });
      } else {
        setState(() => isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('PDF下载失败')),
        );
      }
    } catch (e) {
      setState(() => isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('下载出错: $e')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Show')),
      body: isLoading
          ? const Center(child: CircularProgressIndicator())
          : localPdfPath != null
              ? PdfView(path: localPdfPath!)
              : const Center(child: Text('无法加载PDF')),
    );
  }
}

方案二:更换支持网络URL的PDF插件

推荐使用flutter_pdfview(更主流的PDF查看插件,原生支持网络URL、本地文件、字节流等多种加载方式)。

1. 替换依赖

dependencies:
  flutter:
    sdk: flutter
  flutter_pdfview: ^1.2.1

2. 直接加载网络PDF的代码

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

class PdfShowPage extends StatefulWidget {
  const PdfShowPage({Key? key}) : super(key: key);

  @override
  State<PdfShowPage> createState() => _PdfShowPageState();
}

class _PdfShowPageState extends State<PdfShowPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Show')),
      body: PDFView(
        filePath: 'https://10.0.2.2:7272/api/Pdf',
        enableSwipe: true,
        swipeHorizontal: true,
        onError: (error) {
          print('加载错误: $error');
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('加载出错: $error')),
          );
        },
      ),
    );
  }
}

额外注意事项
  1. 安卓网络权限:确保android/app/src/main/AndroidManifest.xml中添加了网络权限:
<uses-permission android:name="android.permission.INTERNET" />
  1. 本地HTTPS证书问题:如果你的ASP.NET Core API使用自签HTTPS证书,需要在安卓配置中允许信任本地证书,或者暂时改用HTTP测试。

内容的提问来源于stack exchange,提问作者Adil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 16:07:10