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

Android模拟器读取PDF崩溃:Lost Connection to Device与插件异常

Android模拟器加载PDF崩溃问题解决办法

针对你使用advanced_pdf_viewer插件在Android模拟器加载PDF时出现的「Lost Connection to Device」崩溃,以及Already closed、MissingPluginException错误,提供以下解决思路:

一、修复插件原生链接问题

  • 执行flutter clean清理项目缓存,再运行flutter pub get重新拉取依赖
  • 卸载模拟器上的现有APP,重新执行flutter run,确保插件的Android原生代码正确编译安装
  • 检查android/app/build.gradle中的minSdkVersion,该插件要求最低SDK版本为21,若低于此版本需调整

二、优化PDF加载逻辑,避免流提前关闭

直接通过URL加载PDF可能导致网络流被提前释放,建议先将文件下载到本地再加载:

import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;

class _FilePageState extends State<FilePage> {
  Future<File> _downloadFile(String url, String fileName) async {
    final directory = await getApplicationDocumentsDirectory();
    final file = File('${directory.path}/$fileName');
    final response = await http.get(Uri.parse(url));
    await file.writeAsBytes(response.bodyBytes);
    return file;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => true,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.indigo[900],
          title: Text(widget.file!.name.split('.').first),
          centerTitle: true,
        ),
        body: FutureBuilder(
          future: _downloadFile(widget.file!.url, widget.file!.name),
          builder: (context, snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.waiting:
              case ConnectionState.active:
                return const Center(child: CircularProgressIndicator());
              default:
                if (snapshot.hasError) {
                  return const Center(child: Text('文件下载失败'));
                }
                final localFile = snapshot.data as File;
                return FutureBuilder<PDFDocument>(
                  future: PDFDocument.fromFile(localFile),
                  builder: (ctx, pdfSnapshot) {
                    if (pdfSnapshot.connectionState == ConnectionState.waiting) {
                      return const Center(child: CircularProgressIndicator());
                    }
                    if (pdfSnapshot.hasError) {
                      return const Center(child: Text('PDF解析失败'));
                    }
                    return PDFViewer(document: pdfSnapshot.data!);
                  },
                );
            }
          },
        ),
      ),
    );
  }
}

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

dependencies:
  path_provider: ^2.1.0
  http: ^1.1.0

三、替换为维护更活跃的PDF插件

advanced_pdf_viewer已长时间未更新,兼容性问题较多,推荐切换到flutter_pdfview(基于AndroidPdfViewer和iOS PDFKit):

  1. 添加依赖:
dependencies:
  flutter_pdfview: ^1.3.2
  1. 修改加载代码:
import 'package:flutter_pdfview/flutter_pdfview.dart';

// 沿用上面的_downloadFile方法,加载时替换为PDFView
return PDFView(
  filePath: localFile.path,
  autoSpacing: true,
  pageFling: true,
  onError: (error) => print('加载错误: $error'),
  onPageError: (page, error) => print('第$page页错误: $error'),
);

四、检查Android权限配置

确保android/app/src/main/AndroidManifest.xml中添加了网络权限(加载网络PDF时需要):

<uses-permission android:name="android.permission.INTERNET" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:06:28