Flutter中如何将API返回的图片和PDF分开显示并支持PDF点击预览
解决方案
你可以通过判断文件后缀区分图片和PDF类型,分别渲染对应样式,同时给PDF项加点击跳转逻辑即可实现需求,预期效果如下:
具体实现步骤
- 先引入PDF打开相关依赖(以调用系统阅读器打开PDF为例,你也可以根据需求替换为对应组件实现APP内预览)
在pubspec.yaml中添加依赖:
dependencies: url_launcher: ^6.2.5
- 修改原有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
相关产品推荐
相关产品推荐

