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

Flutter中如何将API返回的图片和PDF分开显示并支持PDF点击预览

解决方案

你可以通过判断文件后缀区分图片和PDF类型,分别渲染对应样式,同时给PDF项加点击跳转逻辑即可实现需求,预期效果如下:
效果示意图

具体实现步骤

  1. 先引入PDF打开相关依赖(以调用系统阅读器打开PDF为例,你也可以根据需求替换为对应组件实现APP内预览)
    在pubspec.yaml中添加依赖:
dependencies:
  url_launcher: ^6.2.5
  1. 修改原有GridView代码,增加类型判断和点击事件:
GridView.count(
  crossAxisCount: 3,
  children: List.generate(document?.length ?? 0, (ind) {
    final String fileUrl = api.getHTTPUri('/${document[ind].documentPath}').toString();
    // 兼容大小写判断是否为PDF文件
    final bool isPdf = fileUrl.toLowerCase().endsWith('.pdf');
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: InkWell(
        onTap: () async {
          if (isPdf) {
            // 点击PDF项时调用系统应用打开文件,也可替换为跳转自定义的APP内预览页面
            await launchUrl(Uri.parse(fileUrl));
          }
        },
        child: CircleAvatar(
          radius: 80,
          backgroundColor: isPdf ? Colors.blue : null,
          backgroundImage: isPdf ? null : NetworkImage(fileUrl),
          child: isPdf ? const Icon(
            Icons.picture_as_pdf,
            color: Colors.white,
            size: 36,
          ) : null,
        ),
      ),
    );
  }),
)

注意事项

  • 安卓端需要在AndroidManifest.xml的<manifest>标签下添加网络权限,才可正常打开网络PDF:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • iOS端需要在Info.plist中添加如下配置,否则无法正常跳转外部应用:
    <key>LSApplicationQueriesSchemes</key>
    <array>
      <string>http</string>
      <string>https</string>
    </array>
    
  • 如果你需要对图片加载错误做兼容,可以给NetworkImage加errorWidget配置,避免加载失败时显示空白。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:57:02